home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 2: Applications / Linux Cubed Series 2 - Applications.iso / editors / emacs / xemacs / xemacs-1.004 / xemacs-1 / xemacs-19.13 / src / sysdep.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-08-15  |  129.5 KB  |  4,967 lines

  1. /* Interfaces to system-dependent kernel and library entries.
  2.    Copyright (C) 1985-1988, 1992-1994 Free Software Foundation, Inc.
  3.    Copyright (C) 1994, 1995 Amdahl Corporation.
  4.    Copyright (C) 1995 Tinker Systems
  5.  
  6. This file is part of XEmacs.
  7.  
  8. XEmacs is free software; you can redistribute it and/or modify it
  9. under the terms of the GNU General Public License as published by the
  10. Free Software Foundation; either version 2, or (at your option) any
  11. later version.
  12.  
  13. XEmacs is distributed in the hope that it will be useful, but WITHOUT
  14. ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  15. FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  16. for more details.
  17.  
  18. You should have received a copy of the GNU General Public License
  19. along with XEmacs; see the file COPYING.  If not, write to the Free
  20. Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  21.  
  22. /* Synched up with: FSF 19.28. */
  23.  
  24. /* Substantially cleaned up by Ben Wing, Dec. 1994 / Jan. 1995. */
  25.  
  26. /* In this file, open, read and write refer to the system calls,
  27.    not our sugared interfaces sys_open, sys_read and sys_write.
  28.  */
  29.  
  30. #define DONT_ENCAPSULATE
  31.  
  32. #include <config.h>
  33. #include "lisp.h"
  34.  
  35. /* ------------------------------- */
  36. /*          basic includes         */
  37. /* ------------------------------- */
  38.  
  39. #ifdef HAVE_X_WINDOWS
  40. #include "device-x.h"
  41. #endif /* HAVE_X_WINDOWS */
  42.  
  43. #ifdef HAVE_NEXTSTEP
  44. #include "device-ns.h"
  45. #endif /* HAVE_NEXTSTEP */
  46.  
  47. #include "buffer.h"
  48. #include "events.h"
  49. #include "frame.h"
  50. #include "device-tty.h"
  51. #include "device-stream.h"
  52. #include "redisplay.h"
  53. #include "process.h"
  54. #include "sysdep.h"
  55. #include "window.h"
  56.  
  57. #include <setjmp.h>
  58. #include "sysfile.h"
  59. #include "syswait.h"
  60. #include "sysdir.h"
  61. #include "systime.h"
  62.  
  63. /* ------------------------------- */
  64. /*           VMS includes          */
  65. /* ------------------------------- */
  66.  
  67. #ifdef VMS
  68. #include <ttdef.h>
  69. #include <tt2def.h>
  70. #include <iodef.h>
  71. #include <ssdef.h>
  72. #include <descrip.h>
  73. #include <fibdef.h>
  74. #include <atrdef.h>
  75. #undef F_SETFL
  76. #ifndef RAB$C_BID
  77. #include <rab.h>
  78. #endif
  79. #define    MAXIOSIZE ( 32 * PAGESIZE )    /* Don't I/O more than 32 blocks at a time */
  80. #endif /* VMS */
  81.  
  82. /* ------------------------------- */
  83. /*         TTY definitions         */
  84. /* ------------------------------- */
  85.  
  86. #ifdef USG
  87. #include <sys/utsname.h>
  88. #if defined (TIOCGWINSZ) || defined (ISC4_0)
  89. #ifdef NEED_SIOCTL
  90. #include <sys/sioctl.h>
  91. #endif
  92. #ifdef NEED_PTEM_H
  93. #include <sys/stream.h>
  94. #include <sys/ptem.h>
  95. #endif
  96. #endif /* TIOCGWINSZ or ISC4_0 */
  97. #endif /* USG */
  98.  
  99. #ifdef DGUX 
  100. #include <sys/stropts.h> 
  101. #endif 
  102.  
  103. /* LPASS8 is new in 4.3, and makes cbreak mode provide all 8 bits.  */
  104. #ifndef LPASS8
  105. #define LPASS8 0
  106. #endif
  107.  
  108. static int baud_convert[] =
  109. #ifdef BAUD_CONVERT
  110.   BAUD_CONVERT;
  111. #else
  112.   {
  113.     0, 50, 75, 110, 135, 150, 200, 300, 600, 1200,
  114.     1800, 2400, 4800, 9600, 19200, 38400
  115.   };
  116. #endif
  117.  
  118. #ifdef AIX
  119. static void hft_init (struct device *d);
  120. static void hft_reset (struct device *d);
  121. #endif
  122.  
  123. /* ------------------------------- */
  124. /*          miscellaneous          */
  125. /* ------------------------------- */
  126.  
  127. #ifndef HAVE_UTIMES
  128. #ifndef HAVE_STRUCT_UTIMBUF
  129. /* We want to use utime rather than utimes, but we couldn't find the
  130.    structure declaration.  We'll use the traditional one.  */
  131. struct utimbuf
  132. {
  133.   long actime;
  134.   long modtime;
  135. };
  136. #endif
  137. #endif
  138.  
  139.  
  140. /************************************************************************/
  141. /*                         subprocess control                           */
  142. /************************************************************************/
  143.  
  144. #ifdef SIGTSTP
  145.  
  146. /* Arrange for character C to be read as the next input from
  147.    the terminal.  */
  148. void
  149. stuff_char (struct device *d, int c)
  150. {
  151.   int input_fd;
  152.  
  153.   assert (DEVICE_IS_TTY (d));
  154.   input_fd = fileno (DEVICE_TTY_DATA (d)->infd);
  155. /* Should perhaps error if in batch mode */
  156. #ifdef TIOCSTI
  157.   ioctl (input_fd, TIOCSTI, &c);
  158. #else /* no TIOCSTI */
  159.   error ("Cannot stuff terminal input characters in this version of Unix.");
  160. #endif /* no TIOCSTI */
  161. }
  162.  
  163. #endif /* SIGTSTP */
  164.  
  165. void
  166. set_exclusive_use (int fd)
  167. {
  168. #ifdef FIOCLEX
  169.   ioctl (fd, FIOCLEX, 0);
  170. #endif
  171.   /* Ok to do nothing if this feature does not exist */
  172. }
  173.  
  174. void
  175. set_descriptor_non_blocking (int fd)
  176. {
  177. /* Stride people say it's a mystery why this is needed
  178.    as well as the O_NDELAY, but that it fails without this.  */
  179.   /* For AIX: Apparently need this for non-blocking reads on sockets.
  180.      It seems that O_NONBLOCK applies only to FIFOs?  From
  181.      lowry@watson.ibm.com (Andy Lowry). */
  182.   /* #### Should this be conditionalized on FIONBIO? */
  183. #if defined (STRIDE) || (defined (pfa) && defined (HAVE_PTYS)) || defined (AIX)
  184.   {
  185.     int one = 1;
  186.     ioctl (fd, FIONBIO, &one);
  187.   }
  188. #endif
  189.  
  190. #ifdef O_NONBLOCK /* The POSIX way */
  191.   fcntl (fd, F_SETFL, O_NONBLOCK);
  192. #elif defined (O_NDELAY)
  193.   fcntl (fd, F_SETFL, O_NDELAY);
  194. #endif /* O_NONBLOCK */
  195. }
  196.  
  197. #if defined (NO_SUBPROCESSES)
  198.  
  199. #ifdef BSD
  200. void
  201. wait_without_blocking (void)
  202. {
  203.   wait3 (0, WNOHANG | WUNTRACED, 0);
  204.   synch_process_alive = 0;
  205. }
  206. #endif /* BSD */
  207.  
  208. #endif /* NO_SUBPROCESSES */
  209.  
  210. int wait_debugging;   /* Set nonzero to make following function work under dbx
  211.                  (at least for bsd).  */
  212.  
  213. /* Wait for subprocess with process id `pid' to terminate and
  214.    make sure it will get eliminated (not remain forever as a zombie). */
  215.  
  216. void
  217. wait_for_termination (int pid)
  218. {
  219.   /* #### With the new improved SIGCHLD handling stuff, there is much
  220.      less danger of race conditions and some of the comments below
  221.      don't apply.  This should be updated. */
  222.   while (1)
  223.     {
  224. #if !defined (NO_SUBPROCESSES)
  225. # ifdef VMS
  226.       int status;
  227.  
  228.       status = SYS$FORCEX (&pid, 0, 0);
  229.       return;
  230. # else /* not VMS */
  231.       /* Note that, whenever any subprocess terminates (asynch. or synch.),
  232.      the SIGCHLD handler will be called and it will call wait().
  233.      Thus we cannot just call wait() ourselves, and we can't block
  234.      SIGCHLD and then call wait(), because then if an asynch.
  235.      process dies while we're waiting for our synch. process,
  236.      Emacs will never notice that the asynch. process died.
  237.  
  238.      So, the general approach we take is to repeatedly block until
  239.      a signal arrives, and then check if our process died
  240.      using kill (pid, 0).  (We could also check the value of
  241.      `synch_process_alive', since the SIGCHLD handler will reset
  242.      that and we know that we're only being called on synchronous
  243.      processes, but this approach is safer.  I don't trust
  244.      the proper delivery of SIGCHLD.
  245.  
  246.      Note also that we cannot use any form of waitpid().
  247.      A loop with WNOHANG will chew up CPU time; better to
  248.      use sleep().  A loop without WNOWAIT will screw up
  249.      the SIGCHLD handler (actually this is not true, if you
  250.      duplicate the exit-status-reaping code; see below).
  251.      A loop with WNOWAIT will result in a race condition
  252.      if the process terminates between the process-status
  253.      check and the call to waitpid(). */
  254.  
  255.       /* Formerly, immediate_quit was set around this function call,
  256.      but that could lead to problems if the QUIT happened when
  257.      SIGCHLD was blocked -- it would remain blocked.  Yet another
  258.      reason why immediate_quit is a bad idea.  In any case, there
  259.      is no reason to resort to this because either the SIGIO or
  260.      the SIGALRM will stop the block in EMACS_WAIT_FOR_SIGNAL(). */
  261.       QUIT;
  262. #  ifdef HAVE_WAITPID
  263.       /* Apparently there are bugs on some systems with the second
  264.      method used below (the EMACS_BLOCK_SIGNAL method), whereby
  265.      zombie processes get left around.  It appears in those cases
  266.      that the SIGCHLD handler is never getting invoked.  It's
  267.      not clear whether this is an Emacs bug or a kernel bug or
  268.      both: on HPUX this problem is observed only with XEmacs,
  269.      but under Solaris 2.4 all sorts of different programs have
  270.      problems with zombies.  The method we use here does not
  271.      require a working SIGCHLD (but will not break if it is
  272.      working), and should be safe. */
  273.       /* 
  274.      We use waitpid() contrary to the remarks above.  There is 
  275.      no race condition, because the three situations when 
  276.      sigchld_handler is invoked should be handled OK:
  277.      - handler invoked before waitpid(): In this case, subprocess 
  278.        status will be set by sigchld_handler.  waitpid() here will 
  279.        return -1 with errno set to ECHILD, which is a valid 
  280.        exit condition.
  281.  
  282.      - handler invoked during waitpid(): as above, except that 
  283.        errno here will be set to EINTR.  This will cause waitpid() to 
  284.        be called again, and this time it will exit with ECHILD.
  285.  
  286.      - handler invoked after waitpid(): The following code will reap 
  287.        the subprocess. In the handler, wait()  will return -1 
  288.        because there is no child to reap, and the handler will exit
  289.        without modifying child subprocess status.
  290.       */
  291.       {
  292.     /* Because the SIGCHLD handler can potentially reap the
  293.     synchronous subprocess, we should take care of that.  */
  294.     
  295.     int ret;
  296.     WAITTYPE w;
  297.     /* Will stay in the do loop as long as:
  298.        1. Process is alive
  299.        2. Ctrl-G is not pressed */
  300.     do
  301.       {
  302.         QUIT;
  303.         ret = waitpid (pid, &w, 0);
  304.         /* waitpid returns 0 if the process is still alive. */
  305.       }
  306.     while (ret == 0 || (ret == -1 && errno == EINTR));
  307.     
  308.     /* On exiting the loop, ret will be -1, with errno set to 
  309.        ECHILD if the child has already been reaped, eg in the 
  310.        signal handler.  */
  311.  
  312.     if (! (ret == pid || (ret == -1 && errno == ECHILD)))
  313.       {
  314.         /* We've had some error condition here.  Per POSIX, the
  315.            only other possibilities are:
  316.            EFAULT (bus error accessing arg 2) or EINVAL (incorrect
  317.            arguments), which are both program bugs.
  318.          
  319.            Since implementations may add their own error
  320.            indicators on top, we ignore it by default.
  321.            */
  322.         
  323.         break;
  324.       }
  325.  
  326.     /* Set synch process globals.  This is can also happen 
  327.        in sigchld_handler, and that code is duplicated. */
  328.     if (ret == pid)
  329.       { /* Update the global sigchld stats. */
  330.         synch_process_alive = 0;
  331.         if (WIFEXITED (w))
  332.           synch_process_retcode = WRETCODE (w);
  333.         else if (WIFSIGNALED (w))
  334.           synch_process_death = signal_name (WTERMSIG (w));
  335.       }
  336.     break;
  337.       }
  338. #  elif defined (EMACS_BLOCK_SIGNAL) && !defined (BROKEN_WAIT_FOR_SIGNAL) && defined (SIGCHLD)
  339.       if (!wait_debugging)
  340.     {
  341.       EMACS_BLOCK_SIGNAL (SIGCHLD);
  342.       /* Block SIGCHLD from happening during this check,
  343.          to avoid race conditions. */
  344.       if (kill (pid, 0) < 0)
  345.         {
  346.           EMACS_UNBLOCK_SIGNAL (SIGCHLD);
  347.           return;
  348.         }
  349.       else
  350.         /* WARNING: Whatever this macro does *must* not allow SIGCHLD
  351.            to happen between the time that it's reenabled and when we
  352.            begin to block.  Otherwise we may end up blocking for a
  353.            signal that has already arrived and isn't coming again.
  354.            Can you say "race condition"?
  355.            
  356.            I assume that the system calls sigpause() or sigsuspend()
  357.            provide this atomicness.  If you're getting hangs in
  358.            sigpause()/sigsuspend(), then your OS doesn't
  359.            implement this properly (this applies under hpux9,
  360.            for example).  Try defining BROKEN_WAIT_FOR_SIGNAL. */
  361.         EMACS_WAIT_FOR_SIGNAL (SIGCHLD);
  362.       continue;
  363.     }
  364. #  else /* not HAVE_WAITPID and (not EMACS_BLOCK_SIGNAL or
  365.        BROKEN_WAIT_FOR_SIGNAL) */
  366.       /* This approach is kind of cheesy but is guaranteed(?!) to work
  367.      for all systems. */
  368.       if (kill (pid, 0) < 0)
  369.     return;
  370.       sleep (1);
  371. #  endif /* not HAVE_WAITPID and (not EMACS_BLOCK_SIGNAL or
  372.        BROKEN_WAIT_FOR_SIGNAL) */
  373. # endif /* not VMS */
  374. #else /* NO_SUBPROCESSES */
  375.       /* No need to be tricky like above; we can just call wait(). */
  376.       int status;
  377.       /* #### should figure out how to write a wait_allowing_quit().
  378.      Since hardly any systems don't have subprocess support,
  379.      however, there doesn't seem to be much point. */
  380.       status = wait (0);
  381.       if (status == pid)
  382.     return;
  383. #endif /* NO_SUBPROCESSES */
  384.     }
  385. }
  386.  
  387.  
  388. #if !defined (NO_SUBPROCESSES)
  389.  
  390. /*
  391.  *    flush any pending output
  392.  *      (may flush input as well; it does not matter the way we use it)
  393.  */
  394.  
  395. void
  396. flush_pending_output (int channel)
  397. {
  398. #ifdef HAVE_TERMIOS
  399.   /* If we try this, we get hit with SIGTTIN, because
  400.      the child's tty belongs to the child's pgrp. */
  401. #elif defined (TCFLSH)
  402.   ioctl (channel, TCFLSH, 1);
  403. #elif defined (TIOCFLUSH)
  404.   int zero = 0;
  405.   /* 3rd arg should be ignored
  406.      but some 4.2 kernels actually want the address of an int
  407.      and nonzero means something different.  */
  408.   ioctl (channel, TIOCFLUSH, &zero);
  409. #endif
  410. }
  411.  
  412. #ifndef VMS
  413. #ifndef MSDOS
  414. /*  Set up the terminal at the other end of a pseudo-terminal that
  415.     we will be controlling an inferior through.
  416.     It should not echo or do line-editing, since that is done
  417.     in Emacs.  No padding needed for insertion into an Emacs buffer.  */
  418.  
  419. void
  420. child_setup_tty (int out)
  421. {
  422.   struct emacs_tty s;
  423.  
  424.   EMACS_GET_TTY (out, &s);
  425.  
  426. #if defined (HAVE_TERMIO) || defined (HAVE_TERMIOS)
  427.   s.main.c_oflag |= OPOST;    /* Enable output postprocessing */
  428.   s.main.c_oflag &= ~ONLCR;    /* Disable map of NL to CR-NL on output */
  429. #ifdef NLDLY
  430.   s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY|FFDLY);
  431.                   /* No output delays */
  432. #endif
  433.   s.main.c_lflag &= ~ECHO;    /* Disable echo */
  434.   s.main.c_lflag |= ISIG;    /* Enable signals */
  435. #ifdef IUCLC
  436.   s.main.c_iflag &= ~IUCLC;     /* Disable downcasing on input.  */
  437. #endif
  438. #ifdef OLCUC
  439.   s.main.c_oflag &= ~OLCUC;    /* Disable upcasing on output.  */
  440. #endif
  441.   s.main.c_cflag = (s.main.c_cflag & ~CSIZE) | CS8; /* Don't strip 8th bit */
  442. #if 0
  443.   /* Said to be unnecessary:  */
  444.   s.main.c_cc[VMIN] = 1;    /* minimum number of characters to accept  */
  445.   s.main.c_cc[VTIME] = 0;    /* wait forever for at least 1 character  */
  446. #endif
  447.  
  448.   s.main.c_lflag |= ICANON;    /* Enable erase/kill and eof processing */
  449.   s.main.c_cc[VEOF] = 04;    /* insure that EOF is Control-D */
  450.   s.main.c_cc[VERASE] = 0377;    /* disable erase processing */
  451.   s.main.c_cc[VKILL] = 0377;    /* disable kill processing */
  452.  
  453. #ifdef HPUX
  454.   s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
  455. #endif /* HPUX */
  456.  
  457. #ifdef AIX
  458. /* AIX enhanced edit loses NULs, so disable it */
  459. #ifndef IBMR2AIX
  460.   s.main.c_line = 0;
  461.   s.main.c_iflag &= ~ASCEDIT;
  462. #endif
  463.   /* Also, PTY overloads NUL and BREAK.
  464.      don't ignore break, but don't signal either, so it looks like NUL.  */
  465.   s.main.c_iflag &= ~IGNBRK;
  466.   s.main.c_iflag &= ~BRKINT;
  467.   /* QUIT and INTR work better as signals, so disable character forms */
  468.   s.main.c_cc[VINTR] = 0377;
  469. #ifdef SIGNALS_VIA_CHARACTERS
  470.   /* the QUIT and INTR character are used in process_send_signal
  471.      so set them here to something useful.  */
  472.   if (s.main.c_cc[VQUIT] == 0377)
  473.     s.main.c_cc[VQUIT] = '\\'&037;    /* Control-\ */
  474.   if (s.main.c_cc[VINTR] == 0377)
  475.     s.main.c_cc[VINTR] = 'C'&037;    /* Control-C */
  476. #else /* no TIOCGPGRP or no TIOCGLTC or no TIOCGETC */
  477.   /* QUIT and INTR work better as signals, so disable character forms */
  478.   s.main.c_cc[VQUIT] = 0377;
  479.   s.main.c_cc[VINTR] = 0377;
  480.   s.main.c_lflag &= ~ISIG;
  481. #endif /* no TIOCGPGRP or no TIOCGLTC or no TIOCGETC */
  482.   s.main.c_cc[VEOL] = 0377;
  483.   s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
  484. #endif /* AIX */
  485.  
  486. #else /* not HAVE_TERMIO */
  487.  
  488.   s.main.sg_flags &= ~(ECHO | CRMOD | ANYP | ALLDELAY | RAW | LCASE
  489.                | CBREAK | TANDEM);
  490.   s.main.sg_flags |= LPASS8;
  491.   s.main.sg_erase = 0377;
  492.   s.main.sg_kill = 0377;
  493.   s.lmode = LLITOUT | s.lmode;        /* Don't strip 8th bit */
  494.  
  495. #endif /* not HAVE_TERMIO */
  496.  
  497.   EMACS_SET_TTY (out, &s, 0);
  498.  
  499. #ifdef RTU
  500.   {
  501.     int zero = 0;
  502.     ioctl (out, FIOASYNC, &zero);
  503.   }
  504. #endif /* RTU */
  505. }
  506. #endif /* not MSDOS */
  507. #endif /* not VMS */
  508.  
  509. #endif /* not NO_SUBPROCESSES */
  510.  
  511.  
  512. #if !defined (VMS) && !defined (SIGTSTP) && !defined (USG_JOBCTRL)
  513.  
  514. /* Record a signal code and the handler for it.  */
  515. struct save_signal
  516. {
  517.   int code;
  518.   SIGTYPE (*handler) ();
  519. };
  520.  
  521. static void
  522. save_signal_handlers (struct save_signal *saved_handlers)
  523. {
  524.   while (saved_handlers->code)
  525.     {
  526.       saved_handlers->handler
  527.     = (SIGTYPE (*) ()) signal (saved_handlers->code, SIG_IGN);
  528.       saved_handlers++;
  529.     }
  530. }
  531.  
  532. static void
  533. restore_signal_handlers (struct save_signal *saved_handlers)
  534. {
  535.   while (saved_handlers->code)
  536.     {
  537.       signal (saved_handlers->code, saved_handlers->handler);
  538.       saved_handlers++;
  539.     }
  540. }
  541.  
  542. /* Fork a subshell.  */
  543. static void
  544. sys_subshell (void)
  545. {
  546. #ifdef MSDOS
  547.   int st;
  548.   char oldwd[MAXPATHLEN+1]; /* Fixed length is safe on MSDOS.  */
  549. #endif /* MSDOS */
  550.   int pid;
  551.   struct save_signal saved_handlers[5];
  552.   Lisp_Object dir;
  553.   unsigned char *str = 0;
  554.   int len;
  555.  
  556.   saved_handlers[0].code = SIGINT;
  557.   saved_handlers[1].code = SIGQUIT;
  558.   saved_handlers[2].code = SIGTERM;
  559. #ifdef SIGIO
  560.   saved_handlers[3].code = SIGIO;
  561.   saved_handlers[4].code = 0;
  562. #else
  563.   saved_handlers[3].code = 0;
  564. #endif
  565.  
  566.   /* Mentioning current_buffer->buffer would mean including buffer.h,
  567.      which somehow wedges the hp compiler.  So instead...  */
  568.  
  569.   if (NILP (Fboundp (Qdefault_directory)))
  570.     goto xyzzy;
  571.   dir = Fsymbol_value (Qdefault_directory);
  572.   if (!STRINGP (dir))
  573.     goto xyzzy;
  574.   
  575.   dir = expand_and_dir_to_file (Funhandled_file_name_directory (dir), Qnil);
  576.   str = (unsigned char *) alloca (string_ext_length (XSTRING (dir)) + 2);
  577.   len = string_ext_length (XSTRING (dir));
  578.   memcpy (str, string_ext_data (XSTRING (dir)), len);
  579.   /* #### Unix specific */
  580.   if (str[len - 1] != '/') str[len++] = '/';
  581.   str[len] = 0;
  582.  xyzzy:
  583.  
  584.   pid = vfork ();
  585.  
  586.   if (pid == -1)
  587.     error ("Can't spawn subshell");
  588.   if (pid == 0)
  589.   {
  590.     char *sh;
  591.  
  592. #ifdef MSDOS
  593.     getwd (oldwd);
  594. #endif
  595.     sh = (char *) egetenv ("SHELL");
  596.  
  597.     if (sh == 0)
  598.       sh = "sh";
  599.  
  600.     /* Use our buffer's default directory for the subshell.  */
  601.     if (str)
  602.       chdir (str);
  603.  
  604. #if !defined (NO_SUBPROCESSES)
  605.     close_process_descs ();    /* Close Emacs's pipes/ptys */
  606. #endif
  607.  
  608. #ifdef SET_EMACS_PRIORITY
  609.     if (emacs_priority != 0)
  610.       nice (-emacs_priority);   /* Give the new shell the default priority */ 
  611. #endif
  612.  
  613. #ifdef MSDOS
  614.       st = system (sh);
  615.       chdir (oldwd);
  616.       if (st)
  617.         report_file_error ("Can't execute subshell",
  618.                Fcons (build_string (sh), Qnil));
  619. #else /* not MSDOS */
  620.     execlp (sh, sh, 0);
  621.     write (1, "Can't execute subshell", 22);
  622.     _exit (1);
  623. #endif /* not MSDOS */
  624.   }
  625.  
  626.   save_signal_handlers (saved_handlers);
  627.   synch_process_alive = 1;
  628.   wait_for_termination (pid);
  629.   restore_signal_handlers (saved_handlers);
  630. }
  631.  
  632. #endif /* !defined (VMS) && !defined (SIGTSTP) && !defined (USG_JOBCTRL) */
  633.  
  634.  
  635.  
  636. /* Suspend the Emacs process; give terminal to its superior.  */
  637. void
  638. sys_suspend (void)
  639. {
  640. #ifdef VMS
  641.   /* "Foster" parentage allows emacs to return to a subprocess that attached
  642.      to the current emacs as a cheaper than starting a whole new process.  This
  643.      is set up by KEPTEDITOR.COM.  */
  644.   unsigned long parent_id, foster_parent_id;
  645.   char *fpid_string;
  646.  
  647.   fpid_string = getenv ("EMACS_PARENT_PID");
  648.   if (fpid_string != NULL)
  649.     {
  650.       sscanf (fpid_string, "%x", &foster_parent_id);
  651.       if (foster_parent_id != 0)
  652.     parent_id = foster_parent_id;
  653.       else
  654.     parent_id = getppid ();
  655.     }
  656.   else
  657.     parent_id = getppid ();
  658.  
  659.   xfree (fpid_string);        /* On VMS, this was malloc'd */
  660.  
  661.   if (parent_id && parent_id != 0xffffffff)
  662.     {
  663.       SIGTYPE (*oldsig)() = (int) signal (SIGINT, SIG_IGN);
  664.       int status = LIB$ATTACH (&parent_id) & 1;
  665.       signal (SIGINT, oldsig);
  666.       return status;
  667.     }
  668.   else
  669.     {
  670.       struct {
  671.     int    l;
  672.     char    *a;
  673.       } d_prompt;
  674.       d_prompt.l = sizeof ("Emacs: ");        /* Our special prompt */
  675.       d_prompt.a = "Emacs: ";            /* Just a reminder */
  676.       LIB$SPAWN (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, &d_prompt, 0);
  677.       return 1;
  678.     }
  679.   return -1;
  680. #elif defined (SIGTSTP) && !defined (MSDOS)
  681.   {
  682.     int pgrp = EMACS_GET_PROCESS_GROUP ();
  683.     EMACS_KILLPG (pgrp, SIGTSTP);
  684.   }
  685.  
  686. #elif defined (USG_JOBCTRL)
  687.   /* If you don't know what this is don't mess with it */
  688.   ptrace (0, 0, 0, 0);        /* set for ptrace - caught by csh */
  689.   kill (getpid (), SIGQUIT);
  690.  
  691. #else /* No SIGTSTP or USG_JOBCTRL */
  692.  
  693.   /* On a system where suspending is not implemented,
  694.      instead fork a subshell and let it talk directly to the terminal
  695.      while we wait.  */
  696.   sys_subshell ();
  697.  
  698. #endif
  699. }
  700.  
  701. /* Set the logical window size associated with descriptor FD
  702.    to HEIGHT and WIDTH.  This is used mainly with ptys.  */
  703.  
  704. int
  705. set_window_size (int fd, int height, int width)
  706. {
  707. #ifdef TIOCSWINSZ
  708.  
  709.   /* BSD-style.  */
  710.   struct winsize size;
  711.   size.ws_row = height;
  712.   size.ws_col = width;
  713.  
  714.   if (ioctl (fd, TIOCSWINSZ, &size) == -1)
  715.     return 0; /* error */
  716.   else
  717.     return 1;
  718.  
  719. #elif defined (TIOCSSIZE)
  720.  
  721.   /* SunOS - style.  */
  722.   struct ttysize size;  
  723.   size.ts_lines = height;
  724.   size.ts_cols = width;
  725.  
  726.   if (ioctl (fd, TIOCGSIZE, &size) == -1)
  727.     return 0;
  728.   else
  729.     return 1;
  730. #else
  731.   return -1;
  732. #endif
  733. }
  734.  
  735. #ifdef HAVE_PTYS
  736.  
  737. /* Set up the proper status flags for use of a pty.  */
  738.  
  739. void
  740. setup_pty (int fd)
  741. {
  742.   /* I'm told that TOICREMOTE does not mean control chars
  743.      "can't be sent" but rather that they don't have
  744.      input-editing or signaling effects.
  745.      That should be good, because we have other ways
  746.      to do those things in Emacs.
  747.      However, telnet mode seems not to work on 4.2.
  748.      So TIOCREMOTE is turned off now. */
  749.  
  750.   /* Under hp-ux, if TIOCREMOTE is turned on, some calls
  751.      will hang.  In particular, the "timeout" feature (which
  752.      causes a read to return if there is no data available)
  753.      does this.  Also it is known that telnet mode will hang
  754.      in such a way that Emacs must be stopped (perhaps this
  755.      is the same problem).
  756.      
  757.      If TIOCREMOTE is turned off, then there is a bug in
  758.      hp-ux which sometimes loses data.  Apparently the
  759.      code which blocks the master process when the internal
  760.      buffer fills up does not work.  Other than this,
  761.      though, everything else seems to work fine.
  762.      
  763.      Since the latter lossage is more benign, we may as well
  764.      lose that way.  -- cph */
  765. #if defined (FIONBIO) && defined (SYSV_PTYS)
  766.   {
  767.     int on = 1;
  768.     ioctl (fd, FIONBIO, &on);
  769.   }
  770. #endif
  771. #ifdef IBMRTAIX
  772.   /* On AIX, the parent gets SIGHUP when a pty attached child dies.  So, we */
  773.   /* ignore SIGHUP once we've started a child on a pty.  Note that this may */
  774.   /* cause EMACS not to die when it should, i.e., when its own controlling  */
  775.   /* tty goes away.  I've complained to the AIX developers, and they may    */
  776.   /* change this behavior, but I'm not going to hold my breath.             */
  777.   signal (SIGHUP, SIG_IGN);
  778. #endif
  779. }
  780. #endif /* HAVE_PTYS */
  781.  
  782.  
  783. /************************************************************************/
  784. /*                            TTY control                               */
  785. /************************************************************************/
  786.  
  787. /* ------------------------------------------------------ */
  788. /*                     get baud rate                      */
  789. /* ------------------------------------------------------ */
  790.  
  791. void
  792. init_baud_rate (struct device *d)
  793. {
  794.   if (DEVICE_IS_WIN (d) || DEVICE_IS_STREAM (d))
  795.     {
  796.       DEVICE_BAUD_RATE (d) = 38400;
  797.       return;
  798.     }
  799.  
  800.   assert (DEVICE_IS_TTY (d));
  801.   {
  802.     int input_fd = fileno (DEVICE_TTY_DATA (d)->infd);
  803. #ifdef MSDOS
  804.     DEVICE_TTY_DATA (d)->ospeed = 15;
  805. #elif defined (VMS)
  806.     struct vms_sensemode sg;
  807.     
  808.     SYS$QIOW (0, input_fd, IO$_SENSEMODE, &sg, 0, 0,
  809.           &sg.class, 12, 0, 0, 0, 0 );
  810.     DEVICE_TTY_DATA (d)->ospeed = sg.xmit_baud;
  811. #elif defined (HAVE_TERMIOS)
  812.     struct termios sg;
  813.     
  814.     sg.c_cflag = B9600;
  815.     tcgetattr (input_fd, &sg);
  816.     DEVICE_TTY_DATA (d)->ospeed = cfgetospeed (&sg);
  817. # if defined (USE_GETOBAUD) && defined (getobaud)
  818.     /* m88k-motorola-sysv3 needs this (ghazi@noc.rutgers.edu) 9/1/94. */
  819.     if (DEVICE_TTY_DATA (d)->ospeed == 0)
  820.       DEVICE_TTY_DATA (d)->ospeed = getobaud (sg.c_cflag);
  821. # endif
  822. #elif defined (HAVE_TERMIO)
  823.     struct termio sg;
  824.     
  825.     sg.c_cflag = B9600;
  826. # ifdef HAVE_TCATTR
  827.     tcgetattr (input_fd, &sg);
  828. # else
  829.     ioctl (input_fd, TCGETA, &sg);
  830. # endif
  831.     DEVICE_TTY_DATA (d)->ospeed = sg.c_cflag & CBAUD;
  832. #else /* neither VMS nor TERMIOS nor TERMIO */
  833.     struct sgttyb sg;
  834.     
  835.     sg.sg_ospeed = B9600;
  836.     if (ioctl (input_fd, TIOCGETP, &sg) < 0)
  837.       abort ();
  838.     DEVICE_TTY_DATA (d)->ospeed = sg.sg_ospeed;
  839. #endif
  840.   }
  841.   
  842.   DEVICE_BAUD_RATE (d) =
  843.     (DEVICE_TTY_DATA (d)->ospeed < sizeof baud_convert / sizeof baud_convert[0]
  844.      ? baud_convert[DEVICE_TTY_DATA (d)->ospeed]
  845.      : 9600);
  846.  
  847.   if (DEVICE_BAUD_RATE (d) == 0)
  848.     DEVICE_BAUD_RATE (d) = 1200;
  849. }
  850.  
  851.  
  852. /* ------------------------------------------------------ */
  853. /*                       SIGIO control                    */
  854. /* ------------------------------------------------------ */
  855.  
  856. #ifdef SIGIO
  857.  
  858. static void
  859. init_sigio_on_device (struct device *d)
  860. {
  861.   int filedesc = DEVICE_INFD (d);
  862.  
  863. #if defined (I_SETSIG)
  864.   ioctl (filedesc, I_GETSIG, &DEVICE_OLD_SIGIO_FLAG (d));
  865.   DEVICE_OLD_SIGIO_FLAG (d) &= ~S_INPUT;
  866. #elif defined (FASYNC)
  867.   DEVICE_OLD_SIGIO_FLAG (d) =
  868.     fcntl (filedesc, F_GETFL, 0) & ~FASYNC;
  869. #endif
  870.  
  871. #if defined (FIOSSAIOOWN)
  872.   { /* HPUX stuff */
  873.     int owner = getpid ();
  874.     int ioctl_status;
  875.     if (DEVICE_IS_TTY (d))
  876.     {
  877.       ioctl_status = ioctl (filedesc, FIOGSAIOOWN,
  878.                 &DEVICE_OLD_FCNTL_OWNER (d));
  879.       ioctl_status = ioctl (filedesc, FIOSSAIOOWN, &owner);
  880.     }
  881. #ifdef HAVE_WINDOW_SYSTEM
  882.     else if (!DEVICE_IS_STREAM (d))
  883.       {
  884.     /* Process group for socket should be -pid for delivery to self. */
  885.     owner = -owner;
  886.     ioctl_status = ioctl (filedesc, SIOCGPGRP,
  887.                   &DEVICE_OLD_FCNTL_OWNER (d));
  888.     ioctl_status = ioctl (filedesc, SIOCSPGRP, &owner);
  889.       }
  890. #endif
  891.   }
  892. #elif defined (F_SETOWN) && !defined (F_SETOWN_BUG)
  893.   DEVICE_OLD_FCNTL_OWNER (d) = fcntl (filedesc, F_GETOWN, 0);
  894. # ifdef F_SETOWN_SOCK_NEG
  895.   /* stdin is a socket here */
  896.   fcntl (filedesc, F_SETOWN, -getpid ());
  897. # else
  898.   fcntl (filedesc, F_SETOWN, getpid ());
  899. # endif
  900. #endif
  901. }
  902.  
  903. static void
  904. reset_sigio_on_device (struct device *d)
  905. {
  906.   int filedesc = DEVICE_INFD (d);
  907.  
  908. #if defined (FIOSSAIOOWN)
  909.   { /* HPUX stuff */
  910.     int owner = getpid ();
  911.     int ioctl_status;
  912.     if (DEVICE_IS_TTY (d))
  913.       {
  914.     ioctl_status = ioctl (filedesc, FIOSSAIOOWN,
  915.                   &DEVICE_OLD_FCNTL_OWNER (d));
  916.       }
  917. #ifdef HAVE_WINDOW_SYSTEM
  918.     else if (!DEVICE_IS_STREAM (d))
  919.       {
  920.     /* Process group for socket should be -pid for delivery to self. */
  921.     owner = -owner;
  922.     ioctl_status = ioctl (filedesc, SIOCSPGRP,
  923.                   &DEVICE_OLD_FCNTL_OWNER (d));
  924.       }
  925. #endif
  926.   }
  927. #elif defined (F_SETOWN) && !defined (F_SETOWN_BUG)
  928.   fcntl (filedesc, F_SETOWN, DEVICE_OLD_FCNTL_OWNER (d));
  929. #endif
  930. }
  931.  
  932. static void
  933. request_sigio_on_device (struct device *d)
  934. {
  935.   int filedesc = DEVICE_INFD (d);
  936.  
  937. #if defined (I_SETSIG)
  938.   ioctl (filedesc, I_SETSIG, DEVICE_OLD_SIGIO_FLAG (d) | S_INPUT);
  939. #elif defined (FASYNC)
  940.   fcntl (filedesc, F_SETFL, DEVICE_OLD_SIGIO_FLAG (d) | FASYNC);
  941. #elif defined (FIOSSAIOSTAT)
  942.   {
  943.       /* DG: Changed for HP-UX. HP-UX uses different IOCTLs for
  944.      sockets and other devices for some bizarre reason. We guess
  945.      that an X device is a socket, and tty devices aren't. We then
  946.      use the following crud to do the appropriate thing. */
  947.     int on = 1;
  948.     int ioctl_status;        /* ####DG: check if IOCTL succeeds here. */
  949.     int socket_pgroup = -getpid ();
  950.  
  951.     if (DEVICE_IS_TTY (d))
  952.       {
  953.     ioctl_status = ioctl (filedesc, FIOSSAIOSTAT, &on);
  954.       }
  955. #ifdef HAVE_WINDOW_SYSTEM
  956.     else if (!DEVICE_IS_STREAM (d))
  957.       {
  958.     ioctl_status = ioctl (filedesc, FIOASYNC, &on);
  959.     ioctl_status = ioctl (filedesc, SIOCSPGRP, &socket_pgroup);
  960.       }
  961. #endif
  962.   }
  963. #elif defined (FIOASYNC)
  964.   {
  965.     int on = 1;
  966.     ioctl (filedesc, FIOASYNC, &on);
  967.   }
  968. #endif
  969.  
  970. #if defined (_CX_UX) /* #### Is this crap necessary? */
  971.   EMACS_UNBLOCK_SIGNAL (SIGIO);
  972. #endif
  973. }
  974.  
  975. static void
  976. unrequest_sigio_on_device (struct device *d)
  977. {
  978.   int filedesc = DEVICE_INFD (d);
  979.  
  980. #if defined (I_SETSIG)
  981.   ioctl (filedesc, I_SETSIG, DEVICE_OLD_SIGIO_FLAG (d));
  982. #elif defined (FASYNC)
  983.   fcntl (filedesc, F_SETFL, DEVICE_OLD_SIGIO_FLAG (d));
  984. #elif defined (FIOSSAIOSTAT)
  985.   {
  986.       /* DG: Changed for HP-UX. HP-UX uses different IOCTLs for
  987.      sockets and other devices for some bizarre reason. We guess
  988.      that an X device is a socket, and tty devices aren't. We then
  989.      use the following crud to do the appropriate thing. */
  990.  
  991.     int off = 0;
  992.     int socket_pgroup = 0;
  993.     int ioctl_status;
  994.  
  995.     /* See comment for request_sigio_on_device */
  996.  
  997.     if (DEVICE_IS_TTY (d))
  998.       {
  999.     ioctl_status = ioctl (filedesc, FIOSSAIOSTAT, &off);
  1000.       }
  1001.     else 
  1002.       {
  1003.     ioctl_status = ioctl (filedesc, FIOASYNC, &off);
  1004.     ioctl_status = ioctl (filedesc, SIOCSPGRP, &socket_pgroup);
  1005.       }
  1006.   }
  1007. #elif defined (FIOASYNC)
  1008.   {
  1009.     int off = 0;
  1010.     ioctl (filedesc, FIOASYNC, &off);
  1011.   }
  1012. #endif
  1013.  
  1014. }
  1015.  
  1016. void
  1017. request_sigio (void)
  1018. {
  1019.   Lisp_Object dev;
  1020.   DEVICE_LOOP (dev)
  1021.     {
  1022.       struct device *d;
  1023.  
  1024.       d = XDEVICE (XCAR (dev));
  1025.  
  1026.       if (!DEVICE_IS_STREAM (d))
  1027.     request_sigio_on_device (d);
  1028.     }
  1029. }
  1030.  
  1031. void
  1032. unrequest_sigio (void)
  1033. {
  1034.   Lisp_Object dev;
  1035.   DEVICE_LOOP (dev)
  1036.     {
  1037.       struct device *d;
  1038.  
  1039.       d = XDEVICE (XCAR (dev));
  1040.  
  1041.       if (!DEVICE_IS_STREAM (d))
  1042.     unrequest_sigio_on_device (d);
  1043.     }
  1044. }
  1045.  
  1046. #endif /* SIGIO */
  1047.  
  1048. /* ------------------------------------------------------ */
  1049. /*             Changing Emacs's process group             */
  1050. /* ------------------------------------------------------ */
  1051.  
  1052. /* Saving and restoring the process group of Emacs's terminal.  */
  1053.  
  1054. /* On some systems, apparently (?!) Emacs must be in its own process
  1055.    group in order to receive SIGIO correctly.  On other systems
  1056.    (e.g. Solaris), it's not required and doing it makes things
  1057.    get fucked up.  So, we only do it when
  1058.    SIGIO_REQUIRES_SEPARATE_PROCESS_GROUP is defined.  Basically,
  1059.    this is only required for BSD 4.2 systems. (Actually, I bet
  1060.    we don't have to do this at all -- those systems also
  1061.    required interrupt input, which we don't support.)
  1062.  
  1063.    If Emacs was in its own process group (i.e. inherited_pgroup ==
  1064.    getpid ()), then we know we're running under a shell with job
  1065.    control (Emacs would never be run as part of a pipeline).
  1066.    Everything is fine.
  1067.  
  1068.    If Emacs was not in its own process group, then we know we're
  1069.    running under a shell (or a caller) that doesn't know how to
  1070.    separate itself from Emacs (like sh).  Emacs must be in its own
  1071.    process group in order to receive SIGIO correctly.  In this
  1072.    situation, we put ourselves in our own pgroup, forcibly set the
  1073.    tty's pgroup to our pgroup, and make sure to restore and reinstate
  1074.    the tty's pgroup just like any other terminal setting.  If
  1075.    inherited_group was not the tty's pgroup, then we'll get a
  1076.    SIGTTmumble when we try to change the tty's pgroup, and a CONT if
  1077.    it goes foreground in the future, which is what should happen.  */
  1078.  
  1079. #ifdef SIGIO_REQUIRES_SEPARATE_PROCESS_GROUP
  1080.  
  1081. static int inherited_pgroup;
  1082. static int inherited_tty_pgroup;
  1083.  
  1084. #endif
  1085.  
  1086. void
  1087. munge_tty_process_group (void)
  1088. {
  1089. #ifdef SIGIO_REQUIRES_SEPARATE_PROCESS_GROUP
  1090.   if (noninteractive)
  1091.     return;
  1092.  
  1093.   /* Only do this munging if we have a device on the controlling
  1094.      terminal.  See the large comment below. */
  1095.  
  1096.   if (DEVICEP (Vcontrolling_terminal) &&
  1097.       DEVICE_LIVE_P (XDEVICE (Vcontrolling_terminal)))
  1098.     {
  1099.       int fd = open ("/dev/tty", O_RDWR, 0);
  1100.       int me = getpid ();
  1101.       EMACS_BLOCK_SIGNAL (SIGTTOU);
  1102.       EMACS_SET_TTY_PROCESS_GROUP (fd, &me);
  1103.       EMACS_UNBLOCK_SIGNAL (SIGTTOU);
  1104.       close (fd);
  1105.     }
  1106. #endif
  1107. }
  1108.  
  1109. /* Split off the foreground process group to Emacs alone.
  1110.    When we are in the foreground, but not started in our own process
  1111.    group, redirect the TTY to point to our own process group.  We need
  1112.    to be in our own process group to receive SIGIO properly.  */
  1113. static void
  1114. munge_process_groups (void)
  1115. {
  1116. #ifdef SIGIO_REQUIRES_SEPARATE_PROCESS_GROUP
  1117.   if (noninteractive)
  1118.     return;
  1119.  
  1120.   EMACS_SEPARATE_PROCESS_GROUP ();
  1121.  
  1122.   munge_tty_process_group ();
  1123. #endif
  1124. }
  1125.  
  1126. void
  1127. unmunge_tty_process_group (void)
  1128. {
  1129. #ifdef SIGIO_REQUIRES_SEPARATE_PROCESS_GROUP
  1130.   {
  1131.     int fd = open ("/dev/tty", O_RDWR, 0);
  1132.     EMACS_BLOCK_SIGNAL (SIGTTOU);
  1133.     EMACS_SET_TTY_PROCESS_GROUP (fd, &inherited_tty_pgroup);
  1134.     EMACS_UNBLOCK_SIGNAL (SIGTTOU);
  1135.     close (fd);
  1136.   }
  1137. #endif
  1138. }
  1139.  
  1140. /* Set the tty to our original foreground group.
  1141.    Also restore the original process group (put us back into sh's
  1142.    process group), so that ^Z will suspend both us and sh. */
  1143. static void
  1144. unmunge_process_groups (void)
  1145. {
  1146. #ifdef SIGIO_REQUIRES_SEPARATE_PROCESS_GROUP
  1147.   if (noninteractive)
  1148.     return;
  1149.  
  1150.   unmunge_tty_process_group ();
  1151.  
  1152.   EMACS_SET_PROCESS_GROUP (inherited_pgroup);
  1153. #endif
  1154. }
  1155.  
  1156. /* According to some old wisdom, we need to be in a separate process
  1157.    group for SIGIO to work correctly (at least on some systems ...).
  1158.    So go ahead and put ourselves into our own process group.  This
  1159.    will fail if we're already in our own process group, but who cares.
  1160.    Also record whether we were in our own process group. (In general,
  1161.    we will already be in our own process group if we were started from
  1162.    a job-control shell like csh, but not if we were started from sh).
  1163.    
  1164.    If we succeeded in changing our process group, then we will no
  1165.    longer be in the foreground process group of our controlling
  1166.    terminal.  Therefore, if we have a device open onto this terminal,
  1167.    we have to change the controlling terminal's foreground process
  1168.    group (otherwise we will get stopped with a SIGTTIN signal when
  1169.    attempting to read from the terminal).  It's important,
  1170.    however, that we do this *only* when we have a device open onto
  1171.    the terminal.  It's a decidedly bad idea to do so otherwise,
  1172.    especially if XEmacs was started from the background. */
  1173.  
  1174. void
  1175. init_process_group (void)
  1176. {
  1177. #ifdef SIGIO_REQUIRES_SEPARATE_PROCESS_GROUP
  1178.   if (! noninteractive)
  1179.     {
  1180.       int fd = open ("/dev/tty", O_RDWR, 0);
  1181.       inherited_pgroup = EMACS_GET_PROCESS_GROUP ();
  1182.       EMACS_GET_TTY_PROCESS_GROUP (fd, &inherited_tty_pgroup);
  1183.       close (fd);
  1184.       EMACS_SEPARATE_PROCESS_GROUP ();
  1185.     }
  1186. #endif
  1187. }
  1188.  
  1189. void
  1190. disconnect_controlling_terminal (void)
  1191. {
  1192. #  ifdef HAVE_SETSID
  1193.         /* Controlling terminals are attached to a session.
  1194.            Create a new session for us; it will have no controlling
  1195.            terminal.  This also, of course, puts us in our own
  1196.            process group. */
  1197.         setsid ();
  1198. #  else
  1199.         /* Put us in our own process group. */
  1200.         EMACS_SEPARATE_PROCESS_GROUP ();
  1201. #    if defined (TIOCNOTTY)
  1202.         /* This is the older way of disconnecting the controlling
  1203.            terminal, on 4.3 BSD.  We must open /dev/tty; using
  1204.            filedesc 0 is not sufficient because it could be
  1205.            something else (e.g. our stdin was redirected to
  1206.            another terminal).
  1207. */
  1208.         {
  1209.           int j = open ("/dev/tty", O_RDWR, 0);
  1210.           ioctl (j, TIOCNOTTY, 0);
  1211.           close (j);
  1212.         }
  1213. #    endif /* TIOCNOTTY */
  1214.         /*
  1215.            On systems without TIOCNOTTY and without
  1216.            setsid(), we don't need to do anything more to
  1217.            disconnect our controlling terminal.  Here is
  1218.            what the man page for termio(7) from a SYSV 3.2
  1219.            system says:
  1220.            
  1221.            "The first terminal file opened by the process group leader
  1222.            of a terminal file not already associated with a process
  1223.            group becomes the control terminal for that process group.
  1224.            The control terminal plays a special role in handling quit
  1225.            and interrupt signals, as discussed below.  The control
  1226.            terminal is inherited by a child process during a fork(2).
  1227.            A process can break this association by changing its process
  1228.            group using setpgrp(2)."
  1229.            
  1230.            */
  1231. #  endif /* not HAVE_SETSID */
  1232. }
  1233.  
  1234.  
  1235. /* ------------------------------------------------------ */
  1236. /*        Getting and setting emacs_tty structures        */
  1237. /* ------------------------------------------------------ */
  1238.  
  1239. /* Set *TC to the parameters associated with the terminal FD.
  1240.    Return zero if all's well, or -1 if we ran into an error we
  1241.    couldn't deal with.  */
  1242. int
  1243. emacs_get_tty (int fd, struct emacs_tty *settings)
  1244. {
  1245.   /* Retrieve the primary parameters - baud rate, character size, etcetera.  */
  1246. #ifdef HAVE_TCATTR
  1247.   /* We have those nifty POSIX tcmumbleattr functions.  */
  1248.   if (tcgetattr (fd, &settings->main) < 0)
  1249.     return -1;
  1250.  
  1251. #else
  1252. #ifdef HAVE_TERMIO
  1253.   /* The SYSV-style interface?  */
  1254.   if (ioctl (fd, TCGETA, &settings->main) < 0)
  1255.     return -1;
  1256.  
  1257. #else
  1258. #ifdef VMS
  1259.   /* Vehemently Monstrous System?  :-)  */
  1260.   if (! (SYS$QIOW (0, fd, IO$_SENSEMODE, settings, 0, 0,
  1261.            &settings->main.class, 12, 0, 0, 0, 0)
  1262.      & 1))
  1263.     return -1;
  1264.  
  1265. #else
  1266. #ifndef MSDOS
  1267.   /* I give up - I hope you have the BSD ioctls.  */
  1268.   if (ioctl (fd, TIOCGETP, &settings->main) < 0)
  1269.     return -1;
  1270. #endif /* not MSDOS */
  1271. #endif /* not VMS */
  1272. #endif /* HAVE_TERMIO */
  1273. #endif /* HAVE_TCATTR */
  1274.  
  1275.   /* Suivant - Do we have to get struct ltchars data?  */
  1276. #ifdef HAVE_LTCHARS
  1277.   if (ioctl (fd, TIOCGLTC, &settings->ltchars) < 0)
  1278.     return -1;
  1279. #endif
  1280.  
  1281.   /* How about a struct tchars and a wordful of lmode bits?  */
  1282. #ifdef HAVE_TCHARS
  1283.   if (ioctl (fd, TIOCGETC, &settings->tchars) < 0
  1284.       || ioctl (fd, TIOCLGET, &settings->lmode) < 0)
  1285.     return -1;
  1286. #endif
  1287.  
  1288.   /* We have survived the tempest.  */
  1289.   return 0;
  1290. }
  1291.  
  1292. /* Set the parameters of the tty on FD according to the contents of
  1293.    *SETTINGS.  If WAITP is non-zero, we wait for all queued output to
  1294.    be written before making the change; otherwise, we forget any
  1295.    queued input and make the change immediately.
  1296.    Return 0 if all went well, and -1 if anything failed.  */
  1297. int
  1298. emacs_set_tty (int fd, struct emacs_tty *settings, int waitp)
  1299. {
  1300.   /* Set the primary parameters - baud rate, character size, etcetera.  */
  1301. #ifdef HAVE_TCATTR
  1302.   int i;
  1303.   /* We have those nifty POSIX tcmumbleattr functions.
  1304.      William J. Smith <wjs@wiis.wang.com> writes:
  1305.      "POSIX 1003.1 defines tcsetattr() to return success if it was
  1306.      able to perform any of the requested actions, even if some
  1307.      of the requested actions could not be performed.
  1308.      We must read settings back to ensure tty setup properly.
  1309.      AIX requires this to keep tty from hanging occasionally."  */
  1310.   /* This makes sure that we don't loop indefinitely in here.  */
  1311.   for (i = 0 ; i < 10 ; i++)
  1312.     if (tcsetattr (fd, waitp ? TCSAFLUSH : TCSADRAIN, &settings->main) < 0)
  1313.       {
  1314.     if (errno == EINTR)
  1315.       continue;
  1316.     else
  1317.       return -1;
  1318.       }
  1319.     else
  1320.       {
  1321.     struct termios new;
  1322.  
  1323.     /* Get the current settings, and see if they're what we asked for.  */
  1324.     tcgetattr (fd, &new);
  1325.     /* We cannot use memcmp on the whole structure here because under
  1326.      * aix386 the termios structure has some reserved field that may
  1327.      * not be filled in.
  1328.      */
  1329.     if (   new.c_iflag == settings->main.c_iflag
  1330.         && new.c_oflag == settings->main.c_oflag
  1331.         && new.c_cflag == settings->main.c_cflag
  1332.         && new.c_lflag == settings->main.c_lflag
  1333.         && memcmp(new.c_cc, settings->main.c_cc, NCCS) == 0)
  1334.       break;
  1335.     else
  1336.       continue;
  1337.       }
  1338. #else
  1339. #ifdef HAVE_TERMIO
  1340.   /* The SYSV-style interface?  */
  1341.   if (ioctl (fd, waitp ? TCSETAW : TCSETAF, &settings->main) < 0)
  1342.     return -1;
  1343.  
  1344. #else
  1345. #ifdef VMS
  1346.   /* Vehemently Monstrous System?  :-)  */
  1347.   if (! (SYS$QIOW (0, fd, IO$_SETMODE, &input_iosb, 0, 0,
  1348.            &settings->main.class, 12, 0, 0, 0, 0)
  1349.      & 1))
  1350.     return -1;
  1351.  
  1352. #else
  1353. #ifndef MSDOS
  1354.   /* I give up - I hope you have the BSD ioctls.  */
  1355.   if (ioctl (fd, (waitp) ? TIOCSETP : TIOCSETN, &settings->main) < 0)
  1356.     return -1;
  1357. #endif /* not MSDOS */
  1358. #endif /* VMS */
  1359. #endif /* HAVE_TERMIO */
  1360. #endif /* HAVE_TCATTR */
  1361.  
  1362.   /* Suivant - Do we have to get struct ltchars data?  */
  1363. #ifdef HAVE_LTCHARS
  1364.   if (ioctl (fd, TIOCSLTC, &settings->ltchars) < 0)
  1365.     return -1;
  1366. #endif
  1367.  
  1368.   /* How about a struct tchars and a wordful of lmode bits?  */
  1369. #ifdef HAVE_TCHARS
  1370.   if (ioctl (fd, TIOCSETC, &settings->tchars) < 0
  1371.       || ioctl (fd, TIOCLSET, &settings->lmode) < 0)
  1372.     return -1;
  1373. #endif
  1374.   
  1375.   /* We have survived the tempest.  */
  1376.   return 0;
  1377. }
  1378.  
  1379.  
  1380. /* ------------------------------------------------------ */
  1381. /*                 Initializing a device                  */
  1382. /* ------------------------------------------------------ */
  1383.  
  1384. /* This may also be defined in stdio,
  1385.    but if so, this does no harm,
  1386.    and using the same name avoids wasting the other one's space.  */
  1387.  
  1388. #if ((defined(USG) || defined(DGUX)) && !defined(__STDC__))
  1389. char _sobuf[BUFSIZ+8];
  1390. #elif defined(sun) && defined(USG) || defined(IRIX5)
  1391. extern unsigned char _sobuf[BUFSIZ+8];
  1392. #else
  1393. char _sobuf[BUFSIZ];
  1394. #endif
  1395.  
  1396. #if defined (TIOCGLTC) && defined (HAVE_LTCHARS) /* HAVE_LTCHARS */
  1397. static struct ltchars new_ltchars = {-1,-1,-1,-1,-1,-1};
  1398. #endif
  1399. #ifdef TIOCGETC /* HAVE_TCHARS */
  1400. #ifdef HAVE_TCHARS
  1401. static struct tchars new_tchars = {-1,-1,-1,-1,-1,-1};
  1402. #endif
  1403. #endif 
  1404.  
  1405. static void
  1406. tty_init_sys_modes_on_device (struct device *d)
  1407. {
  1408.   struct emacs_tty tty;
  1409.   int input_fd, output_fd;
  1410.  
  1411.   input_fd = fileno (DEVICE_TTY_DATA (d)->infd);
  1412.   output_fd = fileno (DEVICE_TTY_DATA (d)->outfd);
  1413.  
  1414.   EMACS_GET_TTY (input_fd, &DEVICE_TTY_DATA (d)->old_tty);
  1415.   tty = DEVICE_TTY_DATA (d)->old_tty;
  1416.  
  1417. #if defined (HAVE_TERMIO) || defined (HAVE_TERMIOS)
  1418. #ifdef DGUX
  1419.   /* This allows meta to be sent on 8th bit.  */
  1420.   tty.main.c_iflag &= ~INPCK;    /* don't check input for parity */
  1421. #endif
  1422.   tty.main.c_iflag |= (IGNBRK);    /* Ignore break condition */
  1423.   tty.main.c_iflag &= ~ICRNL;    /* Disable map of CR to NL on input */
  1424. #ifdef ISTRIP
  1425.   tty.main.c_iflag &= ~ISTRIP;    /* don't strip 8th bit on input */
  1426. #endif
  1427.   tty.main.c_lflag &= ~ECHO;    /* Disable echo */
  1428.   tty.main.c_lflag &= ~ICANON;    /* Disable erase/kill processing */
  1429. #ifdef IEXTEN
  1430.   tty.main.c_lflag &= ~IEXTEN;    /* Disable other editing characters.  */
  1431. #endif
  1432.   tty.main.c_lflag |= ISIG;    /* Enable signals */
  1433.   if (TTY_FLAGS (d).flow_control)
  1434.     {
  1435.       tty.main.c_iflag |= IXON;    /* Enable start/stop output control */
  1436. #ifdef IXANY
  1437.       tty.main.c_iflag &= ~IXANY;
  1438. #endif /* IXANY */
  1439.     }
  1440.   else
  1441.     tty.main.c_iflag &= ~IXON;    /* Disable start/stop output control */
  1442.   tty.main.c_oflag &= ~ONLCR;    /* Disable map of NL to CR-NL 
  1443.                    on output */
  1444.   tty.main.c_oflag &= ~TAB3;    /* Disable tab expansion */
  1445. #ifdef CS8
  1446.   if (TTY_FLAGS (d).meta_key)
  1447.     {
  1448.       tty.main.c_cflag |= CS8;    /* allow 8th bit on input */
  1449.       tty.main.c_cflag &= ~PARENB;/* Don't check parity */
  1450.     }
  1451. #endif
  1452.   if (DEVICE_TTY_DATA (d)->controlling_terminal)
  1453.     {
  1454.       tty.main.c_cc[VINTR] =
  1455.     DEVICE_QUIT_CHAR (d); /* C-g (usually) gives SIGINT */
  1456.       /* Set up C-g for both SIGQUIT and SIGINT.
  1457.      We don't know which we will get, but we handle both alike
  1458.      so which one it really gives us does not matter.  */
  1459.       tty.main.c_cc[VQUIT] = DEVICE_QUIT_CHAR (d);
  1460.     }
  1461.   else
  1462.     {
  1463.       tty.main.c_cc[VINTR] = CDISABLE;
  1464.       tty.main.c_cc[VQUIT] = CDISABLE;
  1465.     }
  1466.   tty.main.c_cc[VMIN] = 1;    /* Input should wait for at
  1467.                    least 1 char */
  1468.   tty.main.c_cc[VTIME] = 0;    /* no matter how long that takes.  */
  1469. #ifdef VSWTCH
  1470.   tty.main.c_cc[VSWTCH] = CDISABLE;    /* Turn off shell layering use
  1471.                        of C-z */
  1472. #endif /* VSWTCH */
  1473.   /* There was some conditionalizing here on (mips or TCATTR), but
  1474.      I think that's wrong.  There was one report of C-y (DSUSP) not being
  1475.      disabled on HP9000s700 systems, and this might fix it. */
  1476. #ifdef VSUSP
  1477.   tty.main.c_cc[VSUSP] = CDISABLE;/* Turn off mips handling of C-z.  */
  1478. #endif /* VSUSP */
  1479. #ifdef V_DSUSP
  1480.   tty.main.c_cc[V_DSUSP] = CDISABLE; /* Turn off mips handling of C-y.  */
  1481. #endif /* V_DSUSP */
  1482. #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP.  */
  1483.   tty.main.c_cc[VDSUSP] = CDISABLE;
  1484. #endif /* VDSUSP */
  1485. #ifdef VLNEXT
  1486.   tty.main.c_cc[VLNEXT] = CDISABLE;
  1487. #endif /* VLNEXT */
  1488. #ifdef VREPRINT
  1489.   tty.main.c_cc[VREPRINT] = CDISABLE;
  1490. #endif /* VREPRINT */
  1491. #ifdef VWERASE
  1492.   tty.main.c_cc[VWERASE] = CDISABLE;
  1493. #endif /* VWERASE */
  1494. #ifdef VDISCARD
  1495.   tty.main.c_cc[VDISCARD] = CDISABLE;
  1496. #endif /* VDISCARD */
  1497. #ifdef VSTART
  1498.   tty.main.c_cc[VSTART] = CDISABLE;
  1499. #endif /* VSTART */
  1500. #ifdef VSTRT
  1501.   tty.main.c_cc[VSTRT] = CDISABLE; /* called VSTRT on some systems */
  1502. #endif /* VSTART */
  1503. #ifdef VSTOP
  1504.   tty.main.c_cc[VSTOP] = CDISABLE;
  1505. #endif /* VSTOP */
  1506. #ifdef AIX
  1507. #ifndef IBMR2AIX
  1508.   /* AIX enhanced edit loses NULs, so disable it */
  1509.   tty.main.c_line = 0;
  1510.   tty.main.c_iflag &= ~ASCEDIT;
  1511. #else
  1512.   tty.main.c_cc[VSTRT] = 255;
  1513.   tty.main.c_cc[VSTOP] = 255;
  1514.   tty.main.c_cc[VSUSP] = 255;
  1515.   tty.main.c_cc[VDSUSP] = 255;
  1516. #endif /* IBMR2AIX */
  1517.   /* Also, PTY overloads NUL and BREAK.
  1518.      don't ignore break, but don't signal either, so it looks like NUL.
  1519.      This really serves a purpose only if running in an XTERM window
  1520.      or via TELNET or the like, but does no harm elsewhere.  */
  1521.   tty.main.c_iflag &= ~IGNBRK;
  1522.   tty.main.c_iflag &= ~BRKINT;
  1523. #endif
  1524. #else /* if not HAVE_TERMIO */
  1525. #ifndef MSDOS
  1526.   tty.main.sg_flags &= ~(ECHO | CRMOD | XTABS);
  1527.   if (TTY_FLAGS (d).meta_key)
  1528.     tty.main.sg_flags |= ANYP;
  1529.   /* #### should we be using RAW mode here? */
  1530.   tty.main.sg_flags |= /* interrupt_input ? RAW : */ CBREAK;
  1531. #endif /* not MSDOS */
  1532. #endif /* not HAVE_TERMIO */
  1533.   
  1534.   /* If going to use CBREAK mode, we must request C-g to interrupt
  1535.      and turn off start and stop chars, etc.  If not going to use
  1536.      CBREAK mode, do this anyway so as to turn off local flow
  1537.      control for user coming over network on 4.2; in this case,
  1538.      only t_stopc and t_startc really matter.  */
  1539. #ifndef HAVE_TERMIO
  1540. #ifdef HAVE_TCHARS
  1541.   /* Note: if not using CBREAK mode, it makes no difference how we
  1542.      set this */
  1543.   tty.tchars = new_tchars;
  1544.   tty.tchars.t_intrc = DEVICE_QUIT_CHAR (d);
  1545.   if (TTY_FLAGS (d).flow_control)
  1546.     {
  1547.       tty.tchars.t_startc = '\021';
  1548.       tty.tchars.t_stopc = '\023';
  1549.     }
  1550.   
  1551.   tty.lmode = LDECCTQ | LLITOUT | LPASS8 | LNOFLSH |
  1552.     DEVICE_TTY_DATA (d)->old_tty.lmode;
  1553.   
  1554. #if defined (ultrix) || defined (__bsdi__)
  1555.   /* Under Ultrix 4.2a, leaving this out doesn't seem to hurt
  1556.      anything, and leaving it in breaks the meta key.  Go figure.  */
  1557.   /* Turning off ONLCR is enough under BSD/386.  Leave the general
  1558.      output post-processing flag alone since for some reason it
  1559.      doesn't get reset after XEmacs goes away. */
  1560.   tty.lmode &= ~LLITOUT;
  1561. #endif
  1562.   
  1563. #endif /* HAVE_TCHARS */
  1564. #endif /* not HAVE_TERMIO */
  1565.   
  1566. #ifdef HAVE_LTCHARS
  1567.   tty.ltchars = new_ltchars;
  1568. #endif /* HAVE_LTCHARS */
  1569. #ifdef MSDOS
  1570.   internal_terminal_init ();
  1571.   dos_ttraw ();
  1572. #endif
  1573.   
  1574.   EMACS_SET_TTY (input_fd, &tty, 0);
  1575.   
  1576.   /* This code added to insure that, if flow-control is not to be used,
  1577.      we have an unlocked terminal at the start. */
  1578.   
  1579. #ifdef TCXONC
  1580.   if (!TTY_FLAGS (d).flow_control) ioctl (input_fd, TCXONC, 1);
  1581. #endif
  1582. #ifndef APOLLO
  1583. #ifdef TIOCSTART
  1584.   if (!TTY_FLAGS (d).flow_control) ioctl (input_fd, TIOCSTART, 0);
  1585. #endif
  1586. #endif
  1587.   
  1588. #ifdef AIXHFT
  1589.   hft_init (d);
  1590. #ifdef IBMR2AIX
  1591.   {
  1592.     /* IBM's HFT device usually thinks a ^J should be LF/CR.
  1593.        We need it to be only LF.  This is the way that is
  1594.        done. */
  1595.     struct termio tty;
  1596.     
  1597.     if (ioctl (output_fd, HFTGETID, &tty) != -1)
  1598.       write (output_fd, "\033[20l", 5);
  1599.   }
  1600. #endif
  1601. #endif
  1602.  
  1603. #ifdef VMS
  1604.   /*  Appears to do nothing when in PASTHRU mode.
  1605.       SYS$QIOW (0, input_fd, IO$_SETMODE|IO$M_OUTBAND, 0, 0, 0,
  1606.       interrupt_signal, oob_chars, 0, 0, 0, 0);
  1607.       */
  1608.   queue_kbd_input (0);
  1609. #endif /* VMS */
  1610.  
  1611. #ifdef _IOFBF
  1612.   /* This symbol is defined on recent USG systems.
  1613.      Someone says without this call USG won't really buffer the file
  1614.      even with a call to setbuf. */
  1615.   setvbuf (DEVICE_TTY_DATA (d)->outfd, (char *) _sobuf, _IOFBF, sizeof _sobuf);
  1616. #else
  1617.   setbuf (DEVICE_TTY_DATA (d)->outfd, (char *) _sobuf);
  1618. #endif
  1619.   if (DEVICE_IS_TTY (d))
  1620.     set_tty_modes (d);
  1621. }
  1622.  
  1623. void
  1624. init_one_device (struct device *d)
  1625. {
  1626.   if (DEVICE_IS_TTY (d))
  1627.     tty_init_sys_modes_on_device (d);
  1628. #ifdef SIGIO
  1629.   if (!DEVICE_IS_STREAM (d))
  1630.     {
  1631.       init_sigio_on_device (d);
  1632.       request_sigio_on_device (d);
  1633.     }
  1634. #endif
  1635. }
  1636.  
  1637. void
  1638. reinit_initial_device (void)
  1639. {
  1640.   munge_process_groups ();
  1641.   if (DEVICEP (Vcontrolling_terminal) &&
  1642.       DEVICE_LIVE_P (XDEVICE (Vcontrolling_terminal)))
  1643.     init_one_device (XDEVICE (Vcontrolling_terminal));
  1644. }
  1645.  
  1646.  
  1647. /* ------------------------------------------------------ */
  1648. /*                   Other TTY functions                  */
  1649. /* ------------------------------------------------------ */
  1650.  
  1651. #if 0 /* not currently used */
  1652.  
  1653. /* Return nonzero if safe to use tabs in output.
  1654.    At the time this is called, init_sys_modes has not been done yet.  */
  1655.    
  1656. int
  1657. tabs_safe_p (struct device *d)
  1658. {
  1659.   struct emacs_tty tty;
  1660.   int input_fd;
  1661.  
  1662.   /* #### fix this */
  1663.   assert (DEVICE_IS_TTY (d));
  1664.   input_fd = fileno (DEVICE_TTY_DATA (d)->infd);
  1665.  
  1666.   EMACS_GET_TTY (input_fd, &tty);
  1667.   return EMACS_TTY_TABS_OK (&tty);
  1668. }
  1669.  
  1670. #endif
  1671.  
  1672. /* Get terminal size from system.
  1673.    Store number of lines into *heightp and width into *widthp.
  1674.    If zero or a negative number is stored, the value is not valid.  */
  1675.  
  1676. void
  1677. get_tty_device_size (struct device *d, int *widthp, int *heightp)
  1678. {
  1679.   int input_fd;
  1680.  
  1681. #ifdef TIOCGWINSZ
  1682.  
  1683.   /* BSD-style.  */
  1684.   struct winsize size;
  1685.  
  1686.   assert (DEVICE_IS_TTY (d));
  1687.   input_fd = fileno (DEVICE_TTY_DATA (d)->infd);
  1688.  
  1689.   if (ioctl (input_fd, TIOCGWINSZ, &size) == -1)
  1690.     *widthp = *heightp = 0;
  1691.   else
  1692.     {
  1693.       *widthp = size.ws_col;
  1694.       *heightp = size.ws_row;
  1695.     }
  1696.  
  1697. #else
  1698. #ifdef TIOCGSIZE
  1699.  
  1700.   /* SunOS - style.  */
  1701.   struct ttysize size;  
  1702.  
  1703.   assert (DEVICE_IS_TTY (d));
  1704.   input_fd = fileno (DEVICE_TTY_DATA (d)->infd);
  1705.  
  1706.   if (ioctl (input_fd, TIOCGSIZE, &size) == -1)
  1707.     *widthp = *heightp = 0;
  1708.   else
  1709.     {
  1710.       *widthp = size.ts_cols;
  1711.       *heightp = size.ts_lines;
  1712.     }
  1713.  
  1714. #else
  1715. #ifdef VMS
  1716.  
  1717.   struct vms_sensemode tty;
  1718.   
  1719.   assert (DEVICE_IS_TTY (d));
  1720.   input_fd = fileno (DEVICE_TTY_DATA (d)->infd);
  1721.  
  1722.   SYS$QIOW (0, input_fd, IO$_SENSEMODE, &tty, 0, 0,
  1723.         &tty.class, 12, 0, 0, 0, 0);
  1724.   *widthp = tty.scr_wid;
  1725.   *heightp = tty.scr_len;
  1726.  
  1727. #else
  1728. #ifdef MSDOS
  1729.   *widthp = FrameCols ();
  1730.   *heightp = FrameRows ();
  1731. #else /* system doesn't know size */
  1732.  
  1733.   *widthp = 0;
  1734.   *heightp = 0;
  1735.  
  1736. #endif /* not MSDOS */
  1737. #endif /* not VMS */
  1738. #endif /* not SunOS-style */
  1739. #endif /* not BSD-style */
  1740. }
  1741.  
  1742.  
  1743. /* ------------------------------------------------------ */
  1744. /*                   Resetting a device                   */
  1745. /* ------------------------------------------------------ */
  1746.  
  1747. /* Prepare the terminal for exiting Emacs; move the cursor to the
  1748.    bottom of the frame, turn off interrupt-driven I/O, etc.  */
  1749. static void
  1750. tty_reset_sys_modes_on_device (struct device *d)
  1751. {
  1752.   int input_fd, output_fd;
  1753.  
  1754.   input_fd = fileno (DEVICE_TTY_DATA (d)->infd);
  1755.   output_fd = fileno (DEVICE_TTY_DATA (d)->outfd);
  1756.  
  1757. #if defined (IBMR2AIX) && defined (AIXHFT)
  1758.   {
  1759.     /* HFT devices normally use ^J as a LF/CR.  We forced it to 
  1760.        do the LF only.  Now, we need to reset it. */
  1761.     struct termio tty;
  1762.     
  1763.     if (ioctl (output_fd, HFTGETID, &tty) != -1)
  1764.       write (output_fd, "\033[20h", 5);
  1765.   }
  1766. #endif
  1767.  
  1768.   /* #### temporary method of doing this. */
  1769.   {
  1770.     struct frame *f = XFRAME (DEVICE_SELECTED_FRAME (d));
  1771.  
  1772.     tty_clear_region (FRAME_SELECTED_WINDOW (f), DEFAULT_INDEX, 0, f->height,
  1773.               f->width, 1);
  1774.     /* tty_clear_region may move the cursor */
  1775.     cmgoto (f, f->height, 0);
  1776.   }
  1777.  
  1778.   if (DEVICE_IS_TTY (d))
  1779.     reset_tty_modes (d);
  1780.   fflush (DEVICE_TTY_DATA (d)->outfd);
  1781. #if defined (BSD)
  1782.   /* Avoid possible loss of output when changing terminal modes.  */
  1783.   fsync (output_fd);
  1784. #endif
  1785.  
  1786.   while (EMACS_SET_TTY (input_fd, &DEVICE_TTY_DATA (d)->old_tty, 0)
  1787.      < 0 && errno == EINTR)
  1788.     ;
  1789.   
  1790. #ifdef MSDOS
  1791.   dos_ttcooked ();
  1792. #endif
  1793.   
  1794. #ifdef AIXHFT
  1795.   hft_reset (d);
  1796. #endif
  1797. }
  1798.  
  1799. void
  1800. reset_one_device (struct device *d)
  1801. {
  1802.   if (DEVICE_IS_TTY (d))
  1803.     tty_reset_sys_modes_on_device (d);
  1804.   else if (DEVICE_IS_STREAM (d))
  1805.     fflush (DEVICE_STREAM_DATA (d)->outfd);
  1806. #ifdef SIGIO
  1807.   if (!DEVICE_IS_STREAM (d))
  1808.     {
  1809.       unrequest_sigio_on_device (d);
  1810.       reset_sigio_on_device (d);
  1811.     }
  1812. #endif
  1813. }
  1814.  
  1815. void
  1816. reset_all_devices (void)
  1817. {
  1818.   Lisp_Object rest;
  1819.  
  1820.   DEVICE_LOOP (rest)
  1821.     {
  1822.       struct device *d;
  1823.       
  1824.       /* Note: DEVICEP() may not be true because we may be called from
  1825.      within GC (if we hit a fatal error during GC), but XDEVICE()
  1826.      can deal.
  1827.  
  1828.      #### Should probably change DEVICEP() et al. to work on marked
  1829.      objects. */
  1830.       d = XDEVICE (XCAR (rest));
  1831.       
  1832.       if (NILP (DEVICE_SELECTED_FRAME (d)))
  1833.     continue;
  1834.  
  1835.       reset_one_device (d);
  1836.     }
  1837.  
  1838.   unmunge_process_groups ();
  1839. }
  1840.  
  1841. void
  1842. reset_initial_device (void)
  1843. {
  1844.   if (DEVICEP (Vcontrolling_terminal) &&
  1845.       DEVICE_LIVE_P (XDEVICE (Vcontrolling_terminal)))
  1846.     reset_one_device (XDEVICE (Vcontrolling_terminal));
  1847.   unmunge_process_groups ();
  1848. }
  1849.  
  1850.  
  1851. /* ------------------------------------------------------ */
  1852. /*                 extra TTY stuff under AIX              */
  1853. /* ------------------------------------------------------ */
  1854.  
  1855. #ifdef AIXHFT
  1856.  
  1857. /* Called from init_sys_modes.  */
  1858. static void
  1859. hft_init (struct device *d)
  1860. {
  1861.   int junk;
  1862.   int input_fd;
  1863.  
  1864.   assert (DEVICE_IS_TTY (d));
  1865.   input_fd = fileno (DEVICE_TTY_DATA (d)->infd);
  1866.  
  1867.   /* If we're not on an HFT we shouldn't do any of this.  We determine
  1868.      if we are on an HFT by trying to get an HFT error code.  If this
  1869.      call fails, we're not on an HFT. */ 
  1870. #ifdef IBMR2AIX
  1871.   if (ioctl (input_fd, HFQERROR, &junk) < 0)
  1872.     return;
  1873. #else /* not IBMR2AIX */
  1874.   if (ioctl (input_fd, HFQEIO, 0) < 0)
  1875.     return;
  1876. #endif /* not IBMR2AIX */
  1877.  
  1878.   /* On AIX the default hft keyboard mapping uses backspace rather than delete
  1879.      as the rubout key's ASCII code.  Here this is changed.  The bug is that
  1880.      there's no way to determine the old mapping, so in reset_one_device
  1881.      we need to assume that the normal map had been present.  Of course, this
  1882.      code also doesn't help if on a terminal emulator which doesn't understand
  1883.      HFT VTD's. */
  1884.   {
  1885.     struct hfbuf buf;
  1886.     struct hfkeymap keymap;
  1887.  
  1888.     buf.hf_bufp = (char *)&keymap;
  1889.     buf.hf_buflen = sizeof (keymap);
  1890.     keymap.hf_nkeys = 2;
  1891.     keymap.hfkey[0].hf_kpos = 15;
  1892.     keymap.hfkey[0].hf_kstate = HFMAPCHAR | HFSHFNONE;
  1893. #ifdef IBMR2AIX
  1894.     keymap.hfkey[0].hf_keyidh = '<';
  1895. #else /* not IBMR2AIX */
  1896.     keymap.hfkey[0].hf_page = '<';
  1897. #endif /* not IBMR2AIX */
  1898.     keymap.hfkey[0].hf_char = 127;
  1899.     keymap.hfkey[1].hf_kpos = 15;
  1900.     keymap.hfkey[1].hf_kstate = HFMAPCHAR | HFSHFSHFT;
  1901. #ifdef IBMR2AIX
  1902.     keymap.hfkey[1].hf_keyidh = '<';
  1903. #else /* not IBMR2AIX */
  1904.     keymap.hfkey[1].hf_page = '<';
  1905. #endif /* not IBMR2AIX */
  1906.     keymap.hfkey[1].hf_char = 127;
  1907.     hftctl (input_fd, HFSKBD, &buf);
  1908.   }
  1909.   /* #### Should probably set a device TTY flag here. */
  1910. #if 0
  1911.   /* The HFT system on AIX doesn't optimize for scrolling, so it's really ugly
  1912.      at times. */
  1913.   line_ins_del_ok = char_ins_del_ok = 0;
  1914. #endif /* 0 */
  1915. }
  1916.  
  1917. /* Reset the rubout key to backspace. */
  1918.  
  1919. static void
  1920. hft_reset (struct device *d)
  1921. {
  1922.   struct hfbuf buf;
  1923.   struct hfkeymap keymap;
  1924.   int junk;
  1925.   int input_fd;
  1926.  
  1927.   assert (DEVICE_IS_TTY (d));
  1928.   input_fd = fileno (DEVICE_TTY_DATA (d)->infd);
  1929.  
  1930. #ifdef IBMR2AIX
  1931.   if (ioctl (input_fd, HFQERROR, &junk) < 0)
  1932.     return;
  1933. #else /* not IBMR2AIX */
  1934.   if (ioctl (input_fd, HFQEIO, 0) < 0)
  1935.     return;
  1936. #endif /* not IBMR2AIX */
  1937.  
  1938.   buf.hf_bufp = (char *)&keymap;
  1939.   buf.hf_buflen = sizeof (keymap);
  1940.   keymap.hf_nkeys = 2;
  1941.   keymap.hfkey[0].hf_kpos = 15;
  1942.   keymap.hfkey[0].hf_kstate = HFMAPCHAR | HFSHFNONE;
  1943. #ifdef IBMR2AIX
  1944.   keymap.hfkey[0].hf_keyidh = '<';
  1945. #else /* not IBMR2AIX */
  1946.   keymap.hfkey[0].hf_page = '<';
  1947. #endif /* not IBMR2AIX */
  1948.   keymap.hfkey[0].hf_char = 8;
  1949.   keymap.hfkey[1].hf_kpos = 15;
  1950.   keymap.hfkey[1].hf_kstate = HFMAPCHAR | HFSHFSHFT;
  1951. #ifdef IBMR2AIX
  1952.   keymap.hfkey[1].hf_keyidh = '<';
  1953. #else /* not IBMR2AIX */
  1954.   keymap.hfkey[1].hf_page = '<';
  1955. #endif /* not IBMR2AIX */
  1956.   keymap.hfkey[1].hf_char = 8;
  1957.   hftctl (input_fd, HFSKBD, &buf);
  1958. }
  1959.  
  1960. #endif /* AIXHFT */
  1961.  
  1962.  
  1963. /* ------------------------------------------------------ */
  1964. /*                   TTY stuff under VMS                  */
  1965. /* ------------------------------------------------------ */
  1966.  
  1967. /***** #### this is all broken ****/
  1968.  
  1969. #ifdef VMS
  1970.  
  1971. /* Assigning an input channel is done at the start of Emacs execution.
  1972.    This is called each time Emacs is resumed, also, but does nothing
  1973.    because input_chain is no longer zero.  */
  1974.  
  1975. void
  1976. init_vms_input (void)
  1977. {
  1978.   /* #### broken. */
  1979.   int status;
  1980.   
  1981.   if (input_fd == 0)
  1982.     {
  1983.       status = SYS$ASSIGN (&vms_input_dsc, &input_fd, 0, 0);
  1984.       if (! (status & 1))
  1985.     LIB$STOP (status);
  1986.     }
  1987. }
  1988.  
  1989. /* Deassigning the input channel is done before exiting.  */
  1990.  
  1991. void
  1992. stop_vms_input (void)
  1993. {
  1994.   int input_fd = 0; /* #### fileno (DEVICE_TTY_DATA (d)->infd) */
  1995.   return SYS$DASSGN (input_fd);
  1996. }
  1997.  
  1998. static short vms_input_buffer;
  1999.  
  2000. /* Request reading one character into the keyboard buffer.
  2001.    This is done as soon as the buffer becomes empty.  */
  2002.  
  2003. static void
  2004. queue_vms_kbd_input (void)
  2005. {
  2006.   int input_fd = 0; /* #### fileno (DEVICE_TTY_DATA (d)->infd) */
  2007.   int status;
  2008.   vms_waiting_for_ast = 0;
  2009.   vms_stop_input = 0;
  2010.   status = SYS$QIO (0, input_fd, IO$_READVBLK,
  2011.             &vms_input_iosb, vms_kbd_input_ast, 1,
  2012.             &vms_input_buffer, 1, 0, vms_terminator_mask, 0, 0);
  2013. }
  2014.  
  2015. static int vms_input_count;
  2016.  
  2017. /* Ast routine that is called when keyboard input comes in
  2018.    in accord with the SYS$QIO above.  */
  2019.  
  2020. static void
  2021. vms_kbd_input_ast (void)
  2022. {
  2023.   int c = -1;
  2024.   int old_errno = errno;
  2025.   extern EMACS_TIME *input_available_clear_time;
  2026.  
  2027.   if (vms_waiting_for_ast)
  2028.     SYS$SETEF (vms_input_ef);
  2029.   vms_waiting_for_ast = 0;
  2030.   vms_input_count++;
  2031. #ifdef ASTDEBUG
  2032.   if (vms_input_count == 25)
  2033.     exit (1);
  2034.   printf ("Ast # %d,", vms_input_count);
  2035.   printf (" iosb = %x, %x, %x, %x",
  2036.       vms_input_iosb.offset, vms_input_iosb.status, 
  2037.           vms_input_iosb.termlen, vms_input_iosb.term);
  2038. #endif
  2039.   if (vms_input_iosb.offset)
  2040.     {
  2041.       c = vms_input_buffer;
  2042. #ifdef ASTDEBUG
  2043.       printf (", char = 0%o", c);
  2044. #endif
  2045.     }
  2046. #ifdef ASTDEBUG
  2047.   printf ("\n");
  2048.   fflush (stdout);
  2049.   sleep (1);
  2050. #endif
  2051.   if (! vms_stop_input)
  2052.     queue_vms_kbd_input ();
  2053.   if (c >= 0)
  2054.     kbd_buffer_store_char (c);
  2055.  
  2056.   if (input_available_clear_time)
  2057.     EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
  2058.   errno = old_errno;
  2059. }
  2060.  
  2061. #if 0 /* Unused */
  2062. /* Wait until there is something in kbd_buffer.  */
  2063.  
  2064. void
  2065. vms_wait_for_kbd_input (void)
  2066. {
  2067.   /* This function can GC */
  2068.   extern int have_process_input, process_exited;
  2069.  
  2070.   /* If already something, avoid doing system calls.  */
  2071.   if (detect_input_pending (0))
  2072.     {
  2073.       return;
  2074.     }
  2075.   /* Clear a flag, and tell ast routine above to set it.  */
  2076.   SYS$CLREF (vms_input_ef);
  2077.   vms_waiting_for_ast = 1;
  2078.   /* Check for timing error: ast happened while we were doing that.  */
  2079.   if (!detect_input_pending (0))
  2080.     {
  2081.       /* No timing error: wait for flag to be set.  */
  2082.       set_waiting_for_input (0);
  2083.       SYS$WFLOR (vms_input_ef, vms_input_eflist);
  2084.       clear_waiting_for_input (0);
  2085.       if (!detect_input_pending (0))
  2086.     /* Check for subprocess input availability */
  2087.     {
  2088.       int dsp = have_process_input || process_exited;
  2089.  
  2090.       SYS$CLREF (vms_process_ef);
  2091.       if (have_process_input)
  2092.         process_command_input ();
  2093.       if (process_exited)
  2094.         process_exit ();
  2095.       if (dsp)
  2096.         {
  2097.           MARK_MODELINE_CHANGED;
  2098.           redisplay ();
  2099.         }
  2100.     }
  2101.     }
  2102.   vms_waiting_for_ast = 0;
  2103. }
  2104. #endif
  2105.  
  2106. /* Get rid of any pending QIO, when we are about to suspend
  2107.    or when we want to throw away pending input.
  2108.    We wait for a positive sign that the AST routine has run
  2109.    and therefore there is no I/O request queued when we return.
  2110.    SYS$SETAST is used to avoid a timing error.  */
  2111.  
  2112. static void
  2113. vms_end_kbd_input (struct device *d)
  2114. {
  2115.   int input_fd;
  2116.  
  2117.   assert (DEVICE_IS_TTY (d));
  2118.   input_fd = fileno (DEVICE_TTY_DATA (d)->infd);
  2119. #ifdef ASTDEBUG
  2120.   printf ("At end_kbd_input.\n");
  2121.   fflush (stdout);
  2122.   sleep (1);
  2123. #endif
  2124.   if (LIB$AST_IN_PROG ())  /* Don't wait if suspending from kbd_buffer_store_char! */
  2125.     {
  2126.       SYS$CANCEL (input_fd);
  2127.       return;
  2128.     }
  2129.  
  2130.   SYS$SETAST (0);
  2131.   /* Clear a flag, and tell ast routine above to set it.  */
  2132.   SYS$CLREF (vms_input_ef);
  2133.   vms_waiting_for_ast = 1;
  2134.   vms_stop_input = 1;
  2135.   SYS$CANCEL (input_fd);
  2136.   SYS$SETAST (1);
  2137.   SYS$WAITFR (vms_input_ef);
  2138.   vms_waiting_for_ast = 0;
  2139. }
  2140.  
  2141. #if 0 /* Unused */
  2142. /* Wait for either input available or time interval expiry.  */
  2143.  
  2144. void
  2145. vms_input_wait_timeout (int timeval) /* Time to wait, in seconds */
  2146. {
  2147.   int time [2];
  2148.   static int zero = 0;
  2149.   static int large = -10000000;
  2150.  
  2151.   LIB$EMUL (&timeval, &large, &zero, time);       /* Convert to VMS format */
  2152.  
  2153.   /* If already something, avoid doing system calls.  */
  2154.   if (detect_input_pending (0))
  2155.     {
  2156.       return;
  2157.     }
  2158.   /* Clear a flag, and tell ast routine above to set it.  */
  2159.   SYS$CLREF (vms_input_ef);
  2160.   vms_waiting_for_ast = 1;
  2161.   /* Check for timing error: ast happened while we were doing that.  */
  2162.   if (!detect_input_pending (0))
  2163.     {
  2164.       /* No timing error: wait for flag to be set.  */
  2165.       SYS$CANTIM (1, 0);
  2166.       if (SYS$SETIMR (vms_timer_ef, time, 0, 1) & 1) /* Set timer */
  2167.     SYS$WFLOR (vms_timer_ef, vms_timer_eflist);  /* Wait for timer expiry or input */
  2168.     }
  2169.   vms_waiting_for_ast = 0;
  2170. }
  2171. #endif /* 0 */
  2172.  
  2173. #endif /* VMS */
  2174.  
  2175.  
  2176. /************************************************************************/
  2177. /*                    limits of text/data segments                      */
  2178. /************************************************************************/
  2179.  
  2180. /* Note that VMS compiler won't accept defined (CANNOT_DUMP).  */
  2181. #ifndef CANNOT_DUMP
  2182. #define NEED_STARTS
  2183. #endif
  2184.  
  2185. #ifndef SYSTEM_MALLOC
  2186. #ifndef NEED_STARTS
  2187. #define NEED_STARTS
  2188. #endif
  2189. #endif
  2190.  
  2191. #ifdef NEED_STARTS
  2192. /* Some systems that cannot dump also cannot implement these.  */
  2193.  
  2194. /*
  2195.  *    Return the address of the start of the text segment prior to
  2196.  *    doing an unexec.  After unexec the return value is undefined.
  2197.  *    See crt0.c for further explanation and _start.
  2198.  *
  2199.  */
  2200.  
  2201. #if !defined (CANNOT_UNEXEC) && !defined (HAVE_TEXT_START)
  2202. char *
  2203. start_of_text (void)
  2204. {
  2205. #ifdef TEXT_START
  2206.   return ((char *) TEXT_START);
  2207. #else
  2208. #ifdef GOULD
  2209.   extern csrt ();
  2210.   return ((char *) csrt);
  2211. #else /* not GOULD */
  2212.   extern int _start ();
  2213.   return ((char *) _start);
  2214. #endif /* GOULD */
  2215. #endif /* TEXT_START */
  2216. }
  2217. #endif /* not CANNOT_UNEXEC and not HAVE_TEXT_START */
  2218.  
  2219. /*
  2220.  *    Return the address of the start of the data segment prior to
  2221.  *    doing an unexec.  After unexec the return value is undefined.
  2222.  *    See crt0.c for further information and definition of data_start.
  2223.  *
  2224.  *    Apparently, on BSD systems this is etext at startup.  On
  2225.  *    USG systems (swapping) this is highly mmu dependent and
  2226.  *    is also dependent on whether or not the program is running
  2227.  *    with shared text.  Generally there is a (possibly large)
  2228.  *    gap between end of text and start of data with shared text.
  2229.  *
  2230.  *    On Uniplus+ systems with shared text, data starts at a
  2231.  *    fixed address.  Each port (from a given oem) is generally
  2232.  *    different, and the specific value of the start of data can
  2233.  *    be obtained via the UniPlus+ specific "uvar" system call,
  2234.  *    however the method outlined in crt0.c seems to be more portable.
  2235.  *
  2236.  *    Probably what will have to happen when a USG unexec is available,
  2237.  *    at least on UniPlus, is temacs will have to be made unshared so
  2238.  *    that text and data are contiguous.  Then once loadup is complete,
  2239.  *    unexec will produce a shared executable where the data can be
  2240.  *    at the normal shared text boundry and the startofdata variable
  2241.  *    will be patched by unexec to the correct value.
  2242.  *
  2243.  */
  2244.  
  2245. void *
  2246. start_of_data (void)
  2247. {
  2248. #ifdef DATA_START
  2249.   return ((char *) DATA_START);
  2250. #else
  2251. #ifdef ORDINARY_LINK
  2252.   /*
  2253.    * This is a hack.  Since we're not linking crt0.c or pre_crt0.c,
  2254.    * data_start isn't defined.  We take the address of environ, which
  2255.    * is known to live at or near the start of the system crt0.c, and
  2256.    * we don't sweat the handful of bytes that might lose.
  2257.    */
  2258.   extern char **environ;
  2259.  
  2260.   return((char *) &environ);
  2261. #else
  2262.   extern int data_start;
  2263.   return ((char *) &data_start);
  2264. #endif /* ORDINARY_LINK */
  2265. #endif /* DATA_START */
  2266. }
  2267. #endif /* NEED_STARTS (not CANNOT_DUMP or not SYSTEM_MALLOC) */
  2268.  
  2269. #ifndef CANNOT_DUMP
  2270. /* Some systems that cannot dump also cannot implement these.  */
  2271.  
  2272. /*
  2273.  *    Return the address of the end of the text segment prior to
  2274.  *    doing an unexec.  After unexec the return value is undefined.
  2275.  */
  2276.  
  2277. char *
  2278. end_of_text (void)
  2279. {
  2280. #ifdef TEXT_END
  2281.   return ((char *) TEXT_END);
  2282. #else
  2283.   extern int etext;
  2284.   return ((char *) &etext);
  2285. #endif
  2286. }
  2287.  
  2288. /*
  2289.  *    Return the address of the end of the data segment prior to
  2290.  *    doing an unexec.  After unexec the return value is undefined.
  2291.  */
  2292.  
  2293. char *
  2294. end_of_data (void)
  2295. {
  2296. #ifdef DATA_END
  2297.   return ((char *) DATA_END);
  2298. #else
  2299.   extern int edata;
  2300.   return ((char *) &edata);
  2301. #endif
  2302. }
  2303.  
  2304. #endif /* not CANNOT_DUMP */
  2305.  
  2306.  
  2307. /************************************************************************/
  2308. /*                          get the system name                         */
  2309. /************************************************************************/
  2310.  
  2311. /* init_system_name sets up the string for the Lisp function
  2312.    system-name to return. */
  2313.  
  2314. extern Lisp_Object Vsystem_name;
  2315.  
  2316. #if defined (HAVE_SOCKETS) && !defined (VMS)
  2317. # include <sys/socket.h>
  2318. # include <netdb.h>
  2319. #endif /* HAVE_SOCKETS and not VMS */
  2320.  
  2321. void
  2322. init_system_name (void)
  2323. {
  2324. #if defined (VMS)
  2325.   char *sp, *end;
  2326.   if ((sp = egetenv ("SYS$NODE")) == 0)
  2327.     Vsystem_name = build_string ("vax-vms");
  2328.   else if ((end = strchr (sp, ':')) == 0)
  2329.     Vsystem_name = build_string (sp);
  2330.   else
  2331.     Vsystem_name = make_string ((Bufbyte *) sp, end - sp);
  2332. #elif !defined (HAVE_GETHOSTNAME)
  2333.   struct utsname uts;
  2334.   uname (&uts);
  2335.   Vsystem_name = build_string (uts.nodename);
  2336. #else /* HAVE_GETHOSTNAME */
  2337.   int hostname_size = 256;
  2338.   char *hostname = (char *) alloca (hostname_size);
  2339.  
  2340.   /* Try to get the host name; if the buffer is too short, try
  2341.      again.  Apparently, the only indication gethostname gives of
  2342.      whether the buffer was large enough is the presence or absence
  2343.      of a '\0' in the string.  Eech.  */
  2344.   for (;;)
  2345.     {
  2346.       gethostname (hostname, hostname_size - 1);
  2347.       hostname[hostname_size - 1] = '\0';
  2348.  
  2349.       /* Was the buffer large enough for the '\0'?  */
  2350.       if (strlen (hostname) < (size_t) (hostname_size - 1))
  2351.     break;
  2352.  
  2353.       hostname_size <<= 1;
  2354.       hostname = (char *) alloca (hostname_size);
  2355.     }
  2356. # ifdef HAVE_SOCKETS
  2357.   /* Turn the hostname into the official, fully-qualified hostname.
  2358.      Don't do this if we're going to dump; this can confuse system
  2359.      libraries on some machines and make the dumped emacs core dump. */
  2360. #  ifndef CANNOT_DUMP
  2361.   if (initialized)
  2362. #  endif /* not CANNOT_DUMP */
  2363.     {
  2364.       struct hostent *hp;
  2365.       int count;
  2366. #  ifdef TRY_AGAIN
  2367.       for (count = 0; count < 10; count++)
  2368.     {
  2369.       h_errno = 0;
  2370. #  endif
  2371.       /* Some systems can't handle SIGALARM/SIGIO in gethostbyname(). */
  2372.       stop_interrupts ();
  2373.       hp = gethostbyname (hostname);
  2374.       start_interrupts ();
  2375. #  ifdef TRY_AGAIN
  2376.       if (! (hp == 0 && h_errno == TRY_AGAIN))
  2377.         break;
  2378.       Fsleep_for (make_number (1));
  2379.     }
  2380. #  endif
  2381.       if (hp)
  2382.     {
  2383.       CONST char *fqdn = (CONST char *) hp->h_name;
  2384.  
  2385.       if (!strchr (fqdn, '.'))
  2386.         {
  2387.           /* We still don't have a fully qualified domain name.
  2388.          Try to find one in the list of alternate names */
  2389.           char **alias = hp->h_aliases;
  2390.           while (*alias && !strchr (*alias, '.'))
  2391.         alias++;
  2392.           if (*alias)
  2393.         fqdn = *alias;
  2394.         }
  2395.       hostname = (char *) alloca (strlen (fqdn) + 1);
  2396.       strcpy (hostname, fqdn);
  2397.     }
  2398.     }
  2399. # endif /* HAVE_SOCKETS */
  2400.   Vsystem_name = build_string (hostname);
  2401. #endif /* HAVE_GETHOSTNAME and not VMS */
  2402.   {
  2403.     unsigned char *p;
  2404.     int i;
  2405.  
  2406.     for (i = 0, p = string_data (XSTRING (Vsystem_name));
  2407.      i < string_length (XSTRING (Vsystem_name));
  2408.      i++, p++)
  2409.       {
  2410.     if (*p == ' ' || *p == '\t')
  2411.       *p = '-';
  2412.       }
  2413.   }
  2414. }
  2415.  
  2416.  
  2417. /************************************************************************/
  2418. /*                        Emulation of select()                         */
  2419. /************************************************************************/
  2420.  
  2421. #ifndef VMS
  2422. #ifndef HAVE_SELECT
  2423.  
  2424. ERROR: XEmacs requires a working select().
  2425.  
  2426. #endif /* not HAVE_SELECT */
  2427. #endif /* not VMS */
  2428.  
  2429.  
  2430. /************************************************************************/
  2431. /*                      Emulation of signal stuff                       */
  2432. /************************************************************************/
  2433.  
  2434. /* BSD 4.1 crap deleted.  4.2 was released in 1983, for God's sake!  I
  2435.    can't imagine that anyone is actually running that OS any more.
  2436.    You can't use X under it (I think) because there's no select().
  2437.    Anyway, the signal stuff has all been changed.  If someone wants to
  2438.    get this stuff working again, look in the FSF Emacs sources. */
  2439.    
  2440. /* POSIX signals support - DJB */
  2441.  
  2442. #ifdef HAVE_SIGPROCMASK
  2443.  
  2444. /* #### Is there any reason this is static global rather than local? */
  2445. static struct sigaction new_action, old_action;
  2446.  
  2447. signal_handler_t
  2448. sys_do_signal (int signal_number, signal_handler_t action)
  2449. {
  2450. #if 0
  2451.  
  2452.   /* XEmacs works better if system calls are *not* restarted.
  2453.      This allows C-g to interrupt reads and writes, on most systems.
  2454.  
  2455.      #### Another possibility is to just longjmp() out of the signal
  2456.      handler.  According to W.R. Stevens, this should be OK on all
  2457.      systems.  However, I don't want to deal with the potential
  2458.      evil ramifications of this at this point. */
  2459.  
  2460. #ifdef DGUX
  2461.   /* This gets us restartable system calls for efficiency.
  2462.      The "else" code will work as well. */
  2463.   return (berk_signal (signal_number, action));
  2464. #else
  2465.   sigemptyset (&new_action.sa_mask);
  2466.   new_action.sa_handler = action;
  2467. #if defined (SA_RESTART)
  2468.   /* Emacs mostly works better with restartable system services. If this
  2469.    * flag exists, we probably want to turn it on here.
  2470.    */
  2471.   new_action.sa_flags = SA_RESTART;
  2472. #else
  2473.   new_action.sa_flags = 0;
  2474. #endif
  2475.   sigaction (signal_number, &new_action, &old_action);
  2476.   return (old_action.sa_handler);
  2477. #endif /* DGUX */
  2478.  
  2479. #else /* not 0 */
  2480.  
  2481.   sigemptyset (&new_action.sa_mask);
  2482.   new_action.sa_handler = action;
  2483. #if defined (SA_INTERRUPT) /* don't restart system calls, under SunOS */
  2484.   new_action.sa_flags = SA_INTERRUPT;
  2485. #else
  2486.   new_action.sa_flags = 0;
  2487. #endif
  2488.   sigaction (signal_number, &new_action, &old_action);
  2489.   return (old_action.sa_handler);
  2490.  
  2491. #endif /* not 0 */
  2492. }
  2493.  
  2494. #elif defined (HAVE_SIGBLOCK)
  2495.  
  2496. /* We use sigvec() rather than signal() if we have it, because
  2497.    it lets us specify interruptible system calls. */
  2498. signal_handler_t
  2499. sys_do_signal (int signal_number, signal_handler_t action)
  2500. {
  2501.   struct sigvec vec, ovec;
  2502.  
  2503.   vec.sv_handler = action;
  2504.   vec.sv_mask = 0;
  2505. #ifdef SV_INTERRUPT /* don't restart system calls */
  2506.   vec.sv_flags = SV_INTERRUPT;
  2507. #else
  2508.   vec.sv_flags = 0;
  2509. #endif
  2510.  
  2511.   sigvec (signal_number, &vec, &ovec);
  2512.  
  2513.   return (ovec.sv_handler);
  2514. }
  2515.  
  2516. #endif /* HAVE_SIGBLOCK (HAVE_SIGPROCMASK) */
  2517.  
  2518.  
  2519. /************************************************************************/
  2520. /*                        Emulation of strerror()                       */
  2521. /************************************************************************/
  2522.  
  2523. #ifndef HAVE_STRERROR
  2524.  
  2525. #if defined (VMS) && defined (LINK_CRTL_SHARE) && defined (SHAREABLE_LIB_BUG)
  2526.  
  2527. /* Variables declared noshare and initialized in sharable libraries
  2528.    cannot be shared.  The VMS linker incorrectly forces you to use a private
  2529.    version which is uninitialized... If not for this "feature", we
  2530.    could use the C library definition of sys_nerr and sys_errlist. */
  2531. CONST char *sys_errlist[] =
  2532.   {
  2533.     "error 0",
  2534.     "not owner",
  2535.     "no such file or directory",
  2536.     "no such process",
  2537.     "interrupted system call",
  2538.     "I/O error",
  2539.     "no such device or address",
  2540.     "argument list too long",
  2541.     "exec format error",
  2542.     "bad file number",
  2543.     "no child process",
  2544.     "no more processes",
  2545.     "not enough memory",
  2546.     "permission denied",
  2547.     "bad address",
  2548.     "block device required",
  2549.     "mount devices busy",
  2550.     "file exists",
  2551.     "cross-device link",
  2552.     "no such device",
  2553.     "not a directory",
  2554.     "is a directory",
  2555.     "invalid argument",
  2556.     "file table overflow",
  2557.     "too many open files",
  2558.     "not a typewriter",
  2559.     "text file busy",
  2560.     "file too big",
  2561.     "no space left on device",
  2562.     "illegal seek",
  2563.     "read-only file system",
  2564.     "too many links",
  2565.     "broken pipe",
  2566.     "math argument",
  2567.     "result too large",
  2568.     "I/O stream empty",
  2569.     "vax/vms specific error code nontranslatable error"
  2570.   };
  2571. int sys_nerr = countof (sys_errlist);
  2572.  
  2573. #endif /* VMS & LINK_CRTL_SHARE & SHAREABLE_LIB_BUG */
  2574.  
  2575.  
  2576. #if !defined(NeXT) && !defined(__alpha) && !defined(MACH) && !defined(LINUX) && !defined(IRIX) && !defined(__NetBSD__)
  2577. /* Linux added here by Raymond L. Toy <toy@alydar.crd.ge.com> for XEmacs. */
  2578. /* Irix added here by gparker@sni-usa.com for XEmacs. */
  2579. /* NetBSD added here by James R Grinter <jrg@doc.ic.ac.uk> for XEmacs */
  2580. extern CONST char *sys_errlist[];
  2581. extern int sys_nerr;
  2582. #endif
  2583.  
  2584. #ifdef __NetBSD__
  2585. extern char *sys_errlist[];
  2586. extern int sys_nerr;
  2587. #endif
  2588.  
  2589.  
  2590. CONST char *
  2591. strerror (int errnum)
  2592. {
  2593.   if (errnum >= 0 && errnum < sys_nerr)
  2594.     return sys_errlist[errnum];
  2595.   return ((CONST char *) GETTEXT ("Unknown error"));
  2596. }
  2597.  
  2598. #endif /* ! HAVE_STRERROR */
  2599.  
  2600.  
  2601.  
  2602. /************************************************************************/
  2603. /*                    Encapsulations of system calls                    */
  2604. /************************************************************************/
  2605.  
  2606. /***** VMS versions are at the bottom of this file *****/
  2607. /***** MSDOS versions are in msdos.c *****/
  2608.  
  2609. /***************** low-level calls ****************/
  2610.  
  2611. /*
  2612.  *    On USG systems the system calls are INTERRUPTIBLE by signals
  2613.  *    that the user program has elected to catch.  Thus the system call
  2614.  *    must be retried in these cases.  To handle this without massive
  2615.  *    changes in the source code, we remap the standard system call names
  2616.  *    to names for our own functions in sysdep.c that do the system call
  2617.  *    with retries.  Actually, for portability reasons, it is good
  2618.  *    programming practice, as this example shows, to limit all actual
  2619.  *    system calls to a single occurrence in the source.  Sure, this
  2620.  *    adds an extra level of function call overhead but it is almost
  2621.  *    always negligible.   Fred Fish, Unisoft Systems Inc.
  2622.  */
  2623.  
  2624. /* Ben sez: read Dick Gabriel's essay about the Worse Is Better
  2625.    approach to programming and its connection to the silly
  2626.    interruptible-system-call business.  To find it, look at
  2627.    Jamie's home page (http://www.netscape.com/people/jwz). */
  2628.  
  2629. #ifdef ENCAPSULATE_OPEN
  2630.  
  2631. int
  2632. sys_open (CONST char *path, int oflag, ...)
  2633. {
  2634.   int mode;
  2635.   va_list ap;
  2636.   
  2637.   va_start (ap, oflag);
  2638.   mode = va_arg (ap, int);
  2639.   va_end (ap);
  2640.  
  2641.   path = c_charptr_to_external (path);
  2642. #ifdef INTERRUPTIBLE_OPEN
  2643.   {
  2644.     int rtnval;
  2645.     while ((rtnval = open (path, oflag, mode)) == -1
  2646.        && (errno == EINTR));
  2647.     return rtnval;
  2648.   }
  2649. #else
  2650.     return open (path, oflag, mode);
  2651. #endif
  2652. }
  2653.  
  2654. #endif /* ENCAPSULATE_OPEN */
  2655.  
  2656. #ifdef ENCAPSULATE_CLOSE
  2657.  
  2658. int
  2659. sys_close (int fd)
  2660. {
  2661. #ifdef INTERRUPTIBLE_CLOSE
  2662.   int rtnval;
  2663.  
  2664.   while ((rtnval = close (fd)) == -1
  2665.      && (errno == EINTR))
  2666.     ;
  2667.   return rtnval;
  2668. #else
  2669.   return close (fd);
  2670. #endif
  2671. }
  2672.  
  2673. #endif /* ENCAPSULATE_CLOSE */
  2674.  
  2675. int
  2676. sys_read_1 (int fildes, void *buf, unsigned int nbyte, int allow_quit)
  2677. {
  2678. #ifdef VMS
  2679.   return vms_read (fildes, buf, nbyte);
  2680. #else
  2681.   int rtnval;
  2682.  
  2683.   /* No harm in looping regardless of the INTERRUPTIBLE_IO setting. */
  2684.   while ((rtnval = read (fildes, buf, nbyte)) == -1
  2685.      && (errno == EINTR))
  2686.     {
  2687.       if (allow_quit)
  2688.     REALLY_QUIT;
  2689.     }
  2690.   return rtnval;
  2691. #endif
  2692. }
  2693.  
  2694. #ifdef ENCAPSULATE_READ
  2695.  
  2696. int
  2697. sys_read (int fildes, void *buf, unsigned int nbyte)
  2698. {
  2699.   return sys_read_1 (fildes, buf, nbyte, 0);
  2700. }
  2701.  
  2702. #endif /* ENCAPSULATE_READ */
  2703.  
  2704. int
  2705. sys_write_1 (int fildes, CONST void *buf, unsigned int nbyte, int allow_quit)
  2706. {
  2707. #ifdef VMS
  2708.   return vms_write (fildes, buf, nbyte);
  2709. #else
  2710.   int rtnval;
  2711.   int bytes_written = 0;
  2712.   CONST char *b = buf;
  2713.  
  2714.   /* No harm in looping regardless of the INTERRUPTIBLE_IO setting. */
  2715.   while (nbyte > 0)
  2716.     {
  2717.       rtnval = write (fildes, b, nbyte);
  2718.  
  2719.       if (allow_quit)
  2720.     REALLY_QUIT;
  2721.  
  2722.       if (rtnval == -1)
  2723.     {
  2724.       if (errno == EINTR)
  2725.         continue;
  2726.       else
  2727.             return (bytes_written ? bytes_written : -1);
  2728.     }
  2729.       b += rtnval;
  2730.       nbyte -= rtnval;
  2731.       bytes_written += rtnval;
  2732.     }
  2733.   return (bytes_written);
  2734. #endif
  2735. }
  2736.  
  2737. #ifdef ENCAPSULATE_WRITE
  2738.  
  2739. int
  2740. sys_write (int fildes, CONST void *buf, unsigned int nbyte)
  2741. {
  2742.   return sys_write_1 (fildes, buf, nbyte, 0);
  2743. }
  2744.  
  2745. #endif /* ENCAPSULATE_WRITE */
  2746.  
  2747.  
  2748. /**************** stdio calls ****************/
  2749.  
  2750. /* There is at least some evidence that the stdio calls are interruptible
  2751.    just like the normal system calls, at least on some systems.  In any
  2752.    case, it doesn't hurt to encapsulate them. */
  2753.  
  2754. /* #### Should also encapsulate fflush().
  2755.    #### Should conceivably encapsulate getchar() etc.  What a pain! */
  2756.  
  2757. #ifdef ENCAPSULATE_FOPEN
  2758.  
  2759. FILE *
  2760. sys_fopen (CONST char *path, CONST char *type)
  2761. {
  2762.   path = c_charptr_to_external (path);
  2763. #ifdef INTERRUPTIBLE_OPEN
  2764.   {
  2765.     FILE *rtnval;
  2766.     while (!(rtnval = fopen (path, type)) && (errno == EINTR));
  2767.     return rtnval;
  2768.   }
  2769. #else
  2770.   return fopen (path, type);
  2771. #endif
  2772. }
  2773.  
  2774. #endif /* ENCAPSULATE_FOPEN */
  2775.  
  2776. #ifdef ENCAPSULATE_FCLOSE
  2777.  
  2778. int
  2779. sys_fclose (FILE *stream)
  2780. {
  2781. #ifdef INTERRUPTIBLE_CLOSE
  2782.   int rtnval;
  2783.  
  2784.   while ((rtnval = fclose (stream)) == EOF
  2785.      && (errno == EINTR))
  2786.     ;
  2787.   return rtnval;
  2788. #else
  2789.   return fclose (stream);
  2790. #endif
  2791. }
  2792.  
  2793. #endif /* ENCAPSULATE_FCLOSE */
  2794.  
  2795. #ifdef ENCAPSULATE_FREAD
  2796.  
  2797. size_t
  2798. sys_fread (void *ptr, size_t size, size_t nitem, FILE *stream)
  2799. {
  2800. #ifdef INTERRUPTIBLE_IO
  2801.   size_t rtnval;
  2802.   size_t items_read = 0;
  2803.   char *b = (char *) ptr;
  2804.  
  2805.   while (nitem > 0)
  2806.     {
  2807.       rtnval = fread (b, size, nitem, stream);
  2808.       if (rtnval == 0)
  2809.     {
  2810.       if (ferror (stream) && errno == EINTR)
  2811.         continue;
  2812.       else
  2813.             return items_read;
  2814.     }
  2815.       b += size*rtnval;
  2816.       nitem -= rtnval;
  2817.       items_read += rtnval;
  2818.     }
  2819.   return (items_read);
  2820. #else
  2821.   return fread (ptr, size, nitem, stream);
  2822. #endif
  2823. }
  2824.  
  2825. #endif /* ENCAPSULATE_FREAD */
  2826.  
  2827. #ifdef ENCAPSULATE_FWRITE
  2828.  
  2829. size_t
  2830. sys_fwrite (CONST void *ptr, size_t size, size_t nitem, FILE *stream)
  2831. {
  2832. #ifdef INTERRUPTIBLE_IO
  2833.   size_t rtnval;
  2834.   size_t items_written = 0;
  2835.   CONST char *b = (CONST char *) ptr;
  2836.  
  2837.   while (nitem > 0)
  2838.     {
  2839.       rtnval = fwrite (b, size, nitem, stream);
  2840.       if (rtnval == 0)
  2841.     {
  2842.       if (ferror (stream) && errno == EINTR)
  2843.         continue;
  2844.       else
  2845.             return items_written;
  2846.     }
  2847.       b += size*rtnval;
  2848.       nitem -= rtnval;
  2849.       items_written += rtnval;
  2850.     }
  2851.   return (items_written);
  2852. #elif defined (VMS)
  2853.   return vms_fwrite (ptr, size, nitem, stream);
  2854. #else
  2855.   return fwrite (ptr, size, nitem, stream);
  2856. #endif
  2857. }
  2858.  
  2859. #endif /* ENCAPSULATE_FWRITE */
  2860.  
  2861.  
  2862. /********************* directory calls *******************/
  2863.  
  2864. #ifdef ENCAPSULATE_CHDIR
  2865.  
  2866. int
  2867. sys_chdir (CONST char *path)
  2868. {
  2869.   path = c_charptr_to_external (path);
  2870. #ifdef MSDOS
  2871.   return dos_chdir (path);
  2872. #else
  2873.   return chdir (path);
  2874. #endif
  2875. }
  2876.  
  2877. #endif /* ENCAPSULATE_CHDIR */
  2878.  
  2879. #ifdef ENCAPSULATE_MKDIR
  2880.  
  2881. int
  2882. sys_mkdir (CONST char *path, int mode)
  2883. {
  2884.   path = c_charptr_to_external (path);
  2885.   return mkdir (path, mode);
  2886. }
  2887.  
  2888. #endif /* ENCAPSULATE_MKDIR */
  2889.  
  2890. #ifdef ENCAPSULATE_OPENDIR
  2891.  
  2892. DIR *
  2893. sys_opendir (CONST char *filename)
  2894. {
  2895.   filename = c_charptr_to_external (filename);
  2896.   return opendir (filename);
  2897. }
  2898.  
  2899. #endif /* ENCAPSULATE_OPENDIR */
  2900.  
  2901. #ifdef ENCAPSULATE_READDIR
  2902.  
  2903. DIRENTRY *
  2904. sys_readdir (DIR *dirp)
  2905.   /* #### currently we don't do conversions on the incoming data */
  2906.   return readdir (dirp);
  2907. }
  2908.  
  2909. #endif /* ENCAPSULATE_READDIR */
  2910.  
  2911. #ifdef ENCAPSULATE_RMDIR
  2912.  
  2913. int
  2914. sys_rmdir (CONST char *path)
  2915. {
  2916.   path = c_charptr_to_external (path);
  2917.   return rmdir (path);
  2918. }
  2919.  
  2920. #endif /* ENCAPSULATE_RMDIR */
  2921.  
  2922.  
  2923. /***************** file-information calls ******************/
  2924.  
  2925. #ifdef ENCAPSULATE_ACCESS
  2926.  
  2927. int
  2928. sys_access (CONST char *path, int mode)
  2929. {
  2930.   path = c_charptr_to_external (path);
  2931. #ifdef VMS
  2932.   return vms_access (path, mode);
  2933. #else
  2934.   return access (path, mode);
  2935. #endif
  2936. }
  2937.  
  2938. #endif /* ENCAPSULATE_ACCESS */
  2939.  
  2940. #ifdef ENCAPSULATE_LSTAT
  2941.  
  2942. int
  2943. sys_lstat (CONST char *path, struct stat *buf)
  2944. {
  2945.   path = c_charptr_to_external (path);
  2946.   return lstat (path, buf);
  2947. }
  2948.  
  2949. #endif /* ENCAPSULATE_LSTAT */
  2950.  
  2951. #ifdef ENCAPSULATE_READLINK
  2952.  
  2953. int
  2954. sys_readlink (CONST char *path, char *buf, int bufsiz)
  2955. {
  2956.   path = c_charptr_to_external (path);
  2957.   /* #### currently we don't do conversions on the incoming data */
  2958.   return readlink (path, buf, bufsiz);
  2959. }
  2960.  
  2961. #endif /* ENCAPSULATE_READLINK */
  2962.  
  2963. #ifdef ENCAPSULATE_STAT
  2964.  
  2965. int
  2966. sys_stat (CONST char *path, struct stat *buf)
  2967. {
  2968.   path = c_charptr_to_external (path);
  2969.   return stat (path, buf);
  2970. }
  2971.  
  2972. #endif /* ENCAPSULATE_STAT */
  2973.  
  2974.  
  2975. /****************** file-manipulation calls *****************/
  2976.  
  2977. #ifdef ENCAPSULATE_CHMOD
  2978.  
  2979. int
  2980. sys_chmod (CONST char *path, int mode)
  2981. {
  2982.   path = c_charptr_to_external (path);
  2983.   return chmod (path, mode);
  2984. }
  2985.  
  2986. #endif /* ENCAPSULATE_CHMOD */
  2987.  
  2988. #ifdef ENCAPSULATE_CREAT
  2989.  
  2990. int
  2991. sys_creat (CONST char *path, int mode)
  2992. {
  2993.   path = c_charptr_to_external (path);
  2994.   return creat (path, mode);
  2995. }
  2996.  
  2997. #endif /* ENCAPSULATE_CREAT */
  2998.  
  2999. #ifdef ENCAPSULATE_LINK
  3000.  
  3001. int
  3002. sys_link (CONST char *existing, CONST char *new)
  3003. {
  3004.   existing = c_charptr_to_external (existing);
  3005.   new = c_charptr_to_external2 (new);
  3006.   return link (existing, new);
  3007. }
  3008.  
  3009. #endif /* ENCAPSULATE_LINK */
  3010.  
  3011. #ifdef ENCAPSULATE_RENAME
  3012.  
  3013. int
  3014. sys_rename (CONST char *old, CONST char *new)
  3015. {
  3016.   old = c_charptr_to_external (old);
  3017.   new = c_charptr_to_external (new);
  3018.   return rename (old, new);
  3019. }
  3020.  
  3021. #endif /* ENCAPSULATE_RENAME */
  3022.  
  3023. #ifdef ENCAPSULATE_SYMLINK
  3024.  
  3025. int
  3026. sys_symlink (CONST char *name1, CONST char *name2)
  3027. {
  3028.   name1 = c_charptr_to_external (name1);
  3029.   name2 = c_charptr_to_external2 (name2);
  3030.   return symlink (name1, name2);
  3031. }
  3032.  
  3033. #endif /* ENCAPSULATE_SYMLINK */
  3034.  
  3035. #ifdef ENCAPSULATE_UNLINK
  3036.  
  3037. int
  3038. sys_unlink (CONST char *path)
  3039. {
  3040.   path = c_charptr_to_external (path);
  3041.   return unlink (path);
  3042. }
  3043.  
  3044. #endif /* ENCAPSULATE_UNLINK */
  3045.  
  3046.  
  3047. /************************************************************************/
  3048. /*                  Emulations of missing system calls                  */
  3049. /************************************************************************/
  3050.  
  3051. /***** (these are primarily required for USG, it seems) *****/
  3052.  
  3053. /*
  3054.  *    Warning, this function may not duplicate 4.2 action properly
  3055.  *    under error conditions.
  3056.  */
  3057.  
  3058. #ifndef HAVE_GETWD
  3059.  
  3060. char *
  3061. getwd (char *pathname)
  3062. {
  3063.   char *npath, *spath;
  3064. #if !__STDC__ && !defined(STDC_HEADERS)
  3065.   extern char *getcwd ();
  3066. #endif
  3067.  
  3068.   spath = npath = getcwd ((char *) 0, MAXPATHLEN);
  3069.   if (spath == 0)
  3070.     return spath;
  3071.   /* On Altos 3068, getcwd can return @hostname/dir, so discard
  3072.      up to first slash.  Should be harmless on other systems.  */
  3073.   while (*npath && *npath != '/')
  3074.     npath++;
  3075.   strcpy (pathname, npath);
  3076.   xfree (spath);                  /* getcwd uses malloc */
  3077.   return pathname;
  3078. }
  3079.  
  3080. #endif /* HAVE_GETWD */
  3081.  
  3082. /*
  3083.  *    Emulate rename using unlink/link.  Note that this is
  3084.  *    only partially correct.  Also, doesn't enforce restriction
  3085.  *    that files be of same type (regular->regular, dir->dir, etc).
  3086.  */
  3087.  
  3088. #ifndef HAVE_RENAME
  3089.  
  3090. int
  3091. rename (CONST char *from, CONST char *to)
  3092. {
  3093.   if (access (from, 0) == 0)
  3094.     {
  3095.       unlink (to);
  3096.       if (link (from, to) == 0)
  3097.     if (unlink (from) == 0)
  3098.       return (0);
  3099.     }
  3100.   return (-1);
  3101. }
  3102.  
  3103. #endif
  3104.  
  3105. #ifdef HPUX
  3106. #ifndef HAVE_PERROR
  3107.  
  3108. /* HPUX curses library references perror, but as far as we know
  3109.    it won't be called.  Anyway this definition will do for now.  */
  3110.  
  3111. perror (void)
  3112. {
  3113. }
  3114.  
  3115. #endif /* not HAVE_PERROR */
  3116. #endif /* HPUX */
  3117.  
  3118. #ifndef HAVE_DUP2
  3119.  
  3120. /*
  3121.  *    Emulate BSD dup2.  First close newd if it already exists.
  3122.  *    Then, attempt to dup oldd.  If not successful, call dup2 recursively
  3123.  *    until we are, then close the unsuccessful ones.
  3124.  */
  3125.  
  3126. int
  3127. dup2 (int oldd, int newd)
  3128. {
  3129.   int fd, ret;
  3130.   
  3131.   sys_close (newd);
  3132.  
  3133. #ifdef F_DUPFD
  3134.   fd = fcntl (oldd, F_DUPFD, newd);
  3135.   if (fd != newd)
  3136.     error ("can't dup2 (%i,%i) : %s", oldd, newd, strerror (errno));
  3137. #else
  3138.   fd = dup (old);
  3139.   if (fd == -1)
  3140.     return -1;
  3141.   if (fd == new)
  3142.     return new;
  3143.   ret = dup2 (old, new);
  3144.   sys_close (fd);
  3145.   return ret;
  3146. #endif /*  F_DUPFD */
  3147. }
  3148.  
  3149. #endif /* not HAVE_DUP2 */
  3150.  
  3151. /*
  3152.  *    Gettimeofday.  Simulate as much as possible.  Only accurate
  3153.  *    to nearest second.  Emacs doesn't use tzp so ignore it for now.
  3154.  */
  3155.  
  3156. #if !defined (HAVE_GETTIMEOFDAY)
  3157.  
  3158. int
  3159. gettimeofday (struct timeval *tp, struct timezone *tzp)
  3160. {
  3161.   extern long time ();
  3162.  
  3163.   tp->tv_sec = time ((long *)0);    
  3164.   tp->tv_usec = 0;
  3165.   if (tzp != 0)
  3166.     tzp->tz_minuteswest = -1;
  3167.   return (0);
  3168. }
  3169.  
  3170. #endif /* !HAVE_GETTIMEOFDAY */
  3171.   
  3172. /* No need to encapsulate utime and utimes explicitly because all
  3173.    access to those functions goes through the following. */
  3174.  
  3175. int
  3176. set_file_times (char *filename, EMACS_TIME atime, EMACS_TIME mtime)
  3177. {
  3178. #ifdef HAVE_UTIMES
  3179.   struct timeval tv[2];
  3180.   tv[0] = atime;
  3181.   tv[1] = mtime;
  3182.   return utimes (filename, tv);
  3183. #else /* not HAVE_UTIMES */
  3184.   struct utimbuf utb;
  3185.   utb.actime = EMACS_SECS (atime);
  3186.   utb.modtime = EMACS_SECS (mtime);
  3187.   return utime (filename, &utb);
  3188. #endif /* not HAVE_UTIMES */
  3189. }
  3190.  
  3191. #ifndef HAVE_RANDOM
  3192. #ifndef random
  3193.  
  3194. /*
  3195.  *    The BSD random returns numbers in the range of
  3196.  *    0 to 2e31 - 1.  The USG rand returns numbers in the
  3197.  *    range of 0 to 2e15 - 1.  This is probably not significant
  3198.  *    in this usage.
  3199.  */
  3200.  
  3201. long random (void);
  3202. long
  3203. random (void)
  3204. {
  3205. #ifdef HAVE_LRAND48
  3206.   return lrand48 ();
  3207. #else
  3208. /* The BSD rand returns numbers in the range of 0 to 2e31 - 1,
  3209.    with unusable least significant bits.  The USG rand returns
  3210.    numbers in the range of 0 to 2e15 - 1, all usable.  Let us
  3211.    build a usable 30 bit number from either.  */
  3212. #ifdef USG
  3213.   return (rand () << 15) + rand ();
  3214. #else
  3215.   return (rand () & 0x3fff8000) + (rand () >> 16);
  3216. #endif
  3217. #endif /* !HAVE_LRAND48 */
  3218. }
  3219.  
  3220. void srandom (int arg);
  3221. void
  3222. srandom (int arg)
  3223. {
  3224. #ifdef HAVE_LRAND48
  3225.   srand48 ((long) arg);
  3226. #else
  3227.   srand (arg);
  3228. #endif /* !HAVE_LRAND48 */
  3229. }
  3230. #endif /* no random */
  3231. #endif /* no HAVE_RANDOM */
  3232.  
  3233. #ifdef WRONG_NAME_INSQUE
  3234.  
  3235. void
  3236. insque (caddr_t q, caddr_t p)
  3237. {
  3238.   _insque (q,p);
  3239. }
  3240.  
  3241. #endif
  3242.  
  3243.  
  3244. /************************************************************************/
  3245. /*               Strings corresponding to defined signals               */
  3246. /************************************************************************/
  3247.  
  3248. #ifndef HAVE_SYS_SIGLIST
  3249.  
  3250. #ifdef USG
  3251. #ifdef AIX
  3252. CONST char *sys_siglist[NSIG + 1] =
  3253.   {
  3254.     /* AIX has changed the signals a bit */
  3255.     DEFER_GETTEXT ("bogus signal"),            /* 0 */
  3256.     DEFER_GETTEXT ("hangup"),                /* 1  SIGHUP */
  3257.     DEFER_GETTEXT ("interrupt"),            /* 2  SIGINT */
  3258.     DEFER_GETTEXT ("quit"),                /* 3  SIGQUIT */
  3259.     DEFER_GETTEXT ("illegal instruction"),        /* 4  SIGILL */
  3260.     DEFER_GETTEXT ("trace trap"),            /* 5  SIGTRAP */
  3261.     DEFER_GETTEXT ("IOT instruction"),            /* 6  SIGIOT */
  3262.     DEFER_GETTEXT ("crash likely"),            /* 7  SIGDANGER */
  3263.     DEFER_GETTEXT ("floating point exception"),        /* 8  SIGFPE */
  3264.     DEFER_GETTEXT ("kill"),                /* 9  SIGKILL */
  3265.     DEFER_GETTEXT ("bus error"),            /* 10 SIGBUS */
  3266.     DEFER_GETTEXT ("segmentation violation"),        /* 11 SIGSEGV */
  3267.     DEFER_GETTEXT ("bad argument to system call"),    /* 12 SIGSYS */
  3268.     DEFER_GETTEXT ("write on a pipe with no one to read it"), /* 13 SIGPIPE */
  3269.     DEFER_GETTEXT ("alarm clock"),            /* 14 SIGALRM */
  3270.     DEFER_GETTEXT ("software termination signum"),    /* 15 SIGTERM */
  3271.     DEFER_GETTEXT ("user defined signal 1"),        /* 16 SIGUSR1 */
  3272.     DEFER_GETTEXT ("user defined signal 2"),        /* 17 SIGUSR2 */
  3273.     DEFER_GETTEXT ("death of a child"),            /* 18 SIGCLD */
  3274.     DEFER_GETTEXT ("power-fail restart"),        /* 19 SIGPWR */
  3275.     DEFER_GETTEXT ("bogus signal"),            /* 20 */
  3276.     DEFER_GETTEXT ("bogus signal"),            /* 21 */
  3277.     DEFER_GETTEXT ("bogus signal"),            /* 22 */
  3278.     DEFER_GETTEXT ("bogus signal"),            /* 23 */
  3279.     DEFER_GETTEXT ("bogus signal"),            /* 24 */
  3280.     DEFER_GETTEXT ("LAN I/O interrupt"),        /* 25 SIGAIO */
  3281.     DEFER_GETTEXT ("PTY I/O interrupt"),        /* 26 SIGPTY */
  3282.     DEFER_GETTEXT ("I/O intervention required"),    /* 27 SIGIOINT */
  3283.     DEFER_GETTEXT ("HFT grant"),            /* 28 SIGGRANT */
  3284.     DEFER_GETTEXT ("HFT retract"),            /* 29 SIGRETRACT */
  3285.     DEFER_GETTEXT ("HFT sound done"),            /* 30 SIGSOUND */
  3286.     DEFER_GETTEXT ("HFT input ready"),            /* 31 SIGMSG */
  3287.     0
  3288.   };
  3289. #else /* USG, not AIX */
  3290. CONST char *sys_siglist[NSIG + 1] =
  3291.   {
  3292.     DEFER_GETTEXT ("bogus signal"),            /* 0 */
  3293.     DEFER_GETTEXT ("hangup"),                /* 1  SIGHUP */
  3294.     DEFER_GETTEXT ("interrupt"),            /* 2  SIGINT */
  3295.     DEFER_GETTEXT ("quit"),                /* 3  SIGQUIT */
  3296.     DEFER_GETTEXT ("illegal instruction"),        /* 4  SIGILL */
  3297.     DEFER_GETTEXT ("trace trap"),            /* 5  SIGTRAP */
  3298.     DEFER_GETTEXT ("IOT instruction"),            /* 6  SIGIOT */
  3299.     DEFER_GETTEXT ("EMT instruction"),            /* 7  SIGEMT */
  3300.     DEFER_GETTEXT ("floating point exception"),        /* 8  SIGFPE */
  3301.     DEFER_GETTEXT ("kill"),                /* 9  SIGKILL */
  3302.     DEFER_GETTEXT ("bus error"),            /* 10 SIGBUS */
  3303.     DEFER_GETTEXT ("segmentation violation"),        /* 11 SIGSEGV */
  3304.     DEFER_GETTEXT ("bad argument to system call"),    /* 12 SIGSYS */
  3305.     DEFER_GETTEXT ("write on a pipe with no one to read it"), /* 13 SIGPIPE */
  3306.     DEFER_GETTEXT ("alarm clock"),            /* 14 SIGALRM */
  3307.     DEFER_GETTEXT ("software termination signum"),    /* 15 SIGTERM */
  3308.     DEFER_GETTEXT ("user defined signal 1"),        /* 16 SIGUSR1 */
  3309.     DEFER_GETTEXT ("user defined signal 2"),        /* 17 SIGUSR2 */
  3310.     DEFER_GETTEXT ("death of a child"),            /* 18 SIGCLD */
  3311.     DEFER_GETTEXT ("power-fail restart"),        /* 19 SIGPWR */
  3312. #ifdef sun
  3313.     DEFER_GETTEXT ("window size changed"),        /* 20 SIGWINCH */
  3314.     DEFER_GETTEXT ("urgent socket condition"),        /* 21 SIGURG */
  3315.     DEFER_GETTEXT ("pollable event occurred"),        /* 22 SIGPOLL */
  3316.     DEFER_GETTEXT ("stop (cannot be caught or ignored)"), /*  23 SIGSTOP */
  3317.     DEFER_GETTEXT ("user stop requested from tty"),    /* 24 SIGTSTP */
  3318.     DEFER_GETTEXT ("stopped process has been continued"), /* 25 SIGCONT */
  3319.     DEFER_GETTEXT ("background tty read attempted"),    /* 26 SIGTTIN */
  3320.     DEFER_GETTEXT ("background tty write attempted"),    /* 27 SIGTTOU */
  3321.     DEFER_GETTEXT ("virtual timer expired"),        /* 28 SIGVTALRM */
  3322.     DEFER_GETTEXT ("profiling timer expired"),        /* 29 SIGPROF */
  3323.     DEFER_GETTEXT ("exceeded cpu limit"),        /* 30 SIGXCPU */
  3324.     DEFER_GETTEXT ("exceeded file size limit"),        /* 31 SIGXFSZ */
  3325.     DEFER_GETTEXT ("process's lwps are blocked"),    /* 32 SIGWAITING */
  3326.     DEFER_GETTEXT ("special signal used by thread library"), /* 33 SIGLWP */
  3327. #ifdef SIGFREEZE
  3328.     DEFER_GETTEXT ("special signal used by CPR"),        /* 34 SIGFREEZE */
  3329. #endif
  3330. #ifdef SIGTHAW
  3331.     DEFER_GETTEXT ("special signal used by CPR"),        /* 35 SIGTHAW */
  3332. #endif
  3333. #endif /* sun */
  3334.     0
  3335.   };
  3336. #endif /* not AIX */
  3337. #endif /* USG */
  3338. #ifdef DGUX
  3339. CONST char *sys_siglist[NSIG + 1] =
  3340.   {
  3341.     DEFER_GETTEXT ("null signal"),             /*  0 SIGNULL   */
  3342.     DEFER_GETTEXT ("hangup"),                 /*  1 SIGHUP    */
  3343.     DEFER_GETTEXT ("interrupt"),                    /*  2 SIGINT    */
  3344.     DEFER_GETTEXT ("quit"),                 /*  3 SIGQUIT   */
  3345.     DEFER_GETTEXT ("illegal instruction"),         /*  4 SIGILL    */
  3346.     DEFER_GETTEXT ("trace trap"),             /*  5 SIGTRAP   */
  3347.     DEFER_GETTEXT ("abort termination"),         /*  6 SIGABRT   */
  3348.     DEFER_GETTEXT ("SIGEMT"),                 /*  7 SIGEMT    */
  3349.     DEFER_GETTEXT ("floating point exception"),         /*  8 SIGFPE    */
  3350.     DEFER_GETTEXT ("kill"),                 /*  9 SIGKILL   */
  3351.     DEFER_GETTEXT ("bus error"),             /* 10 SIGBUS    */
  3352.     DEFER_GETTEXT ("segmentation violation"),         /* 11 SIGSEGV   */
  3353.     DEFER_GETTEXT ("bad argument to system call"),     /* 12 SIGSYS    */
  3354.     DEFER_GETTEXT ("write on a pipe with no reader"),     /* 13 SIGPIPE   */
  3355.     DEFER_GETTEXT ("alarm clock"),             /* 14 SIGALRM   */
  3356.     DEFER_GETTEXT ("software termination signal"),     /* 15 SIGTERM   */
  3357.     DEFER_GETTEXT ("user defined signal 1"),         /* 16 SIGUSR1   */
  3358.     DEFER_GETTEXT ("user defined signal 2"),         /* 17 SIGUSR2   */
  3359.     DEFER_GETTEXT ("child stopped or terminated"),     /* 18 SIGCLD    */
  3360.     DEFER_GETTEXT ("power-fail restart"),         /* 19 SIGPWR    */
  3361.     DEFER_GETTEXT ("window size changed"),         /* 20 SIGWINCH  */
  3362.     DEFER_GETTEXT ("undefined"),             /* 21           */
  3363.     DEFER_GETTEXT ("pollable event occurred"),         /* 22 SIGPOLL   */
  3364.     DEFER_GETTEXT ("sendable stop signal not from tty"), /* 23 SIGSTOP   */
  3365.     DEFER_GETTEXT ("stop signal from tty"),         /* 24 SIGSTP    */
  3366.     DEFER_GETTEXT ("continue a stopped process"),     /* 25 SIGCONT   */
  3367.     DEFER_GETTEXT ("attempted background tty read"),     /* 26 SIGTTIN   */
  3368.     DEFER_GETTEXT ("attempted background tty write"),     /* 27 SIGTTOU   */
  3369.     DEFER_GETTEXT ("undefined"),             /* 28           */
  3370.     DEFER_GETTEXT ("undefined"),             /* 29           */
  3371.     DEFER_GETTEXT ("undefined"),             /* 30           */
  3372.     DEFER_GETTEXT ("undefined"),             /* 31           */
  3373.     DEFER_GETTEXT ("undefined"),             /* 32           */
  3374.     DEFER_GETTEXT ("socket (TCP/IP) urgent data arrival"), /* 33 SIGURG    */
  3375.     DEFER_GETTEXT ("I/O is possible"),             /* 34 SIGIO     */
  3376.     DEFER_GETTEXT ("exceeded cpu time limit"),         /* 35 SIGXCPU   */
  3377.     DEFER_GETTEXT ("exceeded file size limit"),         /* 36 SIGXFSZ   */
  3378.     DEFER_GETTEXT ("virtual time alarm"),         /* 37 SIGVTALRM */
  3379.     DEFER_GETTEXT ("profiling time alarm"),         /* 38 SIGPROF   */
  3380.     DEFER_GETTEXT ("undefined"),             /* 39           */
  3381.     DEFER_GETTEXT ("file record locks revoked"),     /* 40 SIGLOST   */
  3382.     DEFER_GETTEXT ("undefined"),             /* 41           */
  3383.     DEFER_GETTEXT ("undefined"),             /* 42           */
  3384.     DEFER_GETTEXT ("undefined"),             /* 43           */
  3385.     DEFER_GETTEXT ("undefined"),             /* 44           */
  3386.     DEFER_GETTEXT ("undefined"),             /* 45           */
  3387.     DEFER_GETTEXT ("undefined"),             /* 46           */
  3388.     DEFER_GETTEXT ("undefined"),             /* 47           */
  3389.     DEFER_GETTEXT ("undefined"),             /* 48           */
  3390.     DEFER_GETTEXT ("undefined"),             /* 49           */
  3391.     DEFER_GETTEXT ("undefined"),             /* 50           */
  3392.     DEFER_GETTEXT ("undefined"),             /* 51           */
  3393.     DEFER_GETTEXT ("undefined"),             /* 52           */
  3394.     DEFER_GETTEXT ("undefined"),             /* 53           */
  3395.     DEFER_GETTEXT ("undefined"),             /* 54           */
  3396.     DEFER_GETTEXT ("undefined"),             /* 55           */
  3397.     DEFER_GETTEXT ("undefined"),             /* 56           */
  3398.     DEFER_GETTEXT ("undefined"),             /* 57           */
  3399.     DEFER_GETTEXT ("undefined"),             /* 58           */
  3400.     DEFER_GETTEXT ("undefined"),             /* 59           */
  3401.     DEFER_GETTEXT ("undefined"),             /* 60           */
  3402.     DEFER_GETTEXT ("undefined"),             /* 61           */
  3403.     DEFER_GETTEXT ("undefined"),             /* 62           */
  3404.     DEFER_GETTEXT ("undefined"),             /* 63           */
  3405.     DEFER_GETTEXT ("notification message in mess. queue"), /* 64 SIGDGNOTIFY */
  3406.     0
  3407.   };
  3408. #endif /* DGUX */
  3409.  
  3410. #endif /* ! HAVE_SYS_SIGLIST */
  3411.  
  3412.  
  3413. /************************************************************************/
  3414. /*         Directory routines for systems that don't have them          */
  3415. /************************************************************************/
  3416.  
  3417. #ifdef SYSV_SYSTEM_DIR
  3418.  
  3419. #include <dirent.h>
  3420.  
  3421. #if defined(BROKEN_CLOSEDIR) || !defined(HAVE_CLOSEDIR)
  3422. int
  3423. closedir (DIR *dirp)  /* stream from opendir */
  3424. {
  3425.   int rtnval;
  3426.  
  3427.   rtnval = sys_close (dirp->dd_fd);
  3428.  
  3429.   /* Some systems (like Solaris) allocate the buffer and the DIR all
  3430.      in one block.  Why in the world are we freeing this ourselves
  3431.      anyway?  */
  3432. #if ! (defined (sun) && defined (USG5_4))
  3433.   xfree ((char *) dirp->dd_buf); /* directory block defined in <dirent.h> */
  3434. #endif
  3435.   xfree ((char *) dirp);
  3436.   return (rtnval);
  3437. }
  3438. #endif /* BROKEN_CLOSEDIR or not HAVE_CLOSEDIR */
  3439. #endif /* SYSV_SYSTEM_DIR */
  3440.  
  3441. #ifdef NONSYSTEM_DIR_LIBRARY
  3442.  
  3443. DIR *
  3444. opendir (CONST char *filename)    /* name of directory */
  3445. {
  3446.   DIR *dirp;        /* -> malloc'ed storage */
  3447.   int fd;        /* file descriptor for read */
  3448.   struct stat sbuf;        /* result of fstat */
  3449.  
  3450.   fd = sys_open (filename, 0);
  3451.   if (fd < 0)
  3452.     return 0;
  3453.  
  3454.   if (fstat (fd, &sbuf) < 0
  3455.       || (sbuf.st_mode & S_IFMT) != S_IFDIR
  3456.       || (dirp = (DIR *) malloc (sizeof (DIR))) == 0)
  3457.     {
  3458.       sys_close (fd);
  3459.       return 0;        /* bad luck today */
  3460.     }
  3461.  
  3462.   dirp->dd_fd = fd;
  3463.   dirp->dd_loc = dirp->dd_size = 0;    /* refill needed */
  3464.  
  3465.   return dirp;
  3466. }
  3467.  
  3468. void
  3469. closedir (DIR *dirp)        /* stream from opendir */
  3470. {
  3471.   sys_close (dirp->dd_fd);
  3472.   xfree (dirp);
  3473. }
  3474.  
  3475.  
  3476. #ifndef VMS
  3477. #define DIRSIZ    14
  3478. struct olddir
  3479.   {
  3480.     ino_t od_ino;         /* inode */
  3481.     char od_name[DIRSIZ];    /* filename */
  3482.   };
  3483. #endif /* not VMS */
  3484.  
  3485. static struct direct dir_static; /* simulated directory contents */
  3486.  
  3487. /* ARGUSED */
  3488. struct direct *
  3489. readdir (DIR *dirp)    /* stream from opendir */
  3490. {
  3491. #ifndef VMS
  3492.   struct olddir *dp;    /* -> directory data */
  3493. #else /* VMS */
  3494.   struct dir$_name *dp; /* -> directory data */
  3495.   struct dir$_version *dv; /* -> version data */
  3496. #endif /* VMS */
  3497.  
  3498.   for (; ;)
  3499.     {
  3500.       if (dirp->dd_loc >= dirp->dd_size)
  3501.     dirp->dd_loc = dirp->dd_size = 0;
  3502.  
  3503.       if (dirp->dd_size == 0     /* refill buffer */
  3504.       && (dirp->dd_size = sys_read (dirp->dd_fd, dirp->dd_buf, DIRBLKSIZ)) <= 0)
  3505.     return 0;
  3506.  
  3507. #ifndef VMS
  3508.       dp = (struct olddir *) &dirp->dd_buf[dirp->dd_loc];
  3509.       dirp->dd_loc += sizeof (struct olddir);
  3510.  
  3511.       if (dp->od_ino != 0)    /* not deleted entry */
  3512.     {
  3513.       dir_static.d_ino = dp->od_ino;
  3514.       strncpy (dir_static.d_name, dp->od_name, DIRSIZ);
  3515.       dir_static.d_name[DIRSIZ] = '\0';
  3516.       dir_static.d_namlen = strlen (dir_static.d_name);
  3517.       dir_static.d_reclen = sizeof (struct direct)
  3518.         - MAXNAMLEN + 3
  3519.           + dir_static.d_namlen - dir_static.d_namlen % 4;
  3520.       return &dir_static;    /* -> simulated structure */
  3521.     }
  3522. #else /* VMS */
  3523.       dp = (struct dir$_name *) dirp->dd_buf;
  3524.       if (dirp->dd_loc == 0)
  3525.     dirp->dd_loc = (dp->dir$b_namecount&1) ? dp->dir$b_namecount + 1
  3526.       : dp->dir$b_namecount;
  3527.       dv = (struct dir$_version *)&dp->dir$t_name[dirp->dd_loc];
  3528.       dir_static.d_ino = dv->dir$w_fid_num;
  3529.       dir_static.d_namlen = dp->dir$b_namecount;
  3530.       dir_static.d_reclen = sizeof (struct direct)
  3531.     - MAXNAMLEN + 3
  3532.       + dir_static.d_namlen - dir_static.d_namlen % 4;
  3533.       strncpy (dir_static.d_name, dp->dir$t_name, dp->dir$b_namecount);
  3534.       dir_static.d_name[dir_static.d_namlen] = '\0';
  3535.       dirp->dd_loc = dirp->dd_size; /* only one record at a time */
  3536.       return &dir_static;
  3537. #endif /* VMS */
  3538.     }
  3539. }
  3540.  
  3541. #ifdef VMS
  3542. /* readdirver is just like readdir except it returns all versions of a file
  3543.    as separate entries.  */
  3544.  
  3545. /* ARGUSED */
  3546. struct direct *
  3547. readdirver (DIR *dirp)    /* stream from opendir */
  3548. {
  3549.   struct dir$_name *dp; /* -> directory data */
  3550.   struct dir$_version *dv; /* -> version data */
  3551.  
  3552.   if (dirp->dd_loc >= dirp->dd_size - sizeof (struct dir$_name))
  3553.     dirp->dd_loc = dirp->dd_size = 0;
  3554.  
  3555.   if (dirp->dd_size == 0     /* refill buffer */
  3556.       && (dirp->dd_size = sys_read (dirp->dd_fd, dirp->dd_buf, DIRBLKSIZ)) <= 0)
  3557.     return 0;
  3558.  
  3559.   dp = (struct dir$_name *) dirp->dd_buf;
  3560.   if (dirp->dd_loc == 0)
  3561.     dirp->dd_loc = (dp->dir$b_namecount & 1) ? dp->dir$b_namecount + 1
  3562.            : dp->dir$b_namecount;
  3563.   dv = (struct dir$_version *) &dp->dir$t_name[dirp->dd_loc];
  3564.   strncpy (dir_static.d_name, dp->dir$t_name, dp->dir$b_namecount);
  3565.   sprintf (&dir_static.d_name[dp->dir$b_namecount], ";%d", dv->dir$w_version);
  3566.   dir_static.d_namlen = strlen (dir_static.d_name);
  3567.   dir_static.d_ino = dv->dir$w_fid_num;
  3568.   dir_static.d_reclen = sizeof (struct direct) - MAXNAMLEN + 3
  3569.             + dir_static.d_namlen - dir_static.d_namlen % 4;
  3570.   dirp->dd_loc = ((char *) (++dv) - dp->dir$t_name);
  3571.   return &dir_static;
  3572. }
  3573.  
  3574. #endif /* VMS */
  3575.  
  3576. #endif /* NONSYSTEM_DIR_LIBRARY */
  3577.  
  3578.  
  3579. /* mkdir and rmdir functions, for systems which don't have them.  */
  3580.  
  3581. #ifndef HAVE_MKDIR
  3582. /*
  3583.  * Written by Robert Rother, Mariah Corporation, August 1985.
  3584.  *
  3585.  * If you want it, it's yours.  All I ask in return is that if you
  3586.  * figure out how to do this in a Bourne Shell script you send me
  3587.  * a copy.
  3588.  *                    sdcsvax!rmr or rmr@uscd
  3589.  *
  3590.  * Severely hacked over by John Gilmore to make a 4.2BSD compatible
  3591.  * subroutine.    11Mar86; hoptoad!gnu
  3592.  *
  3593.  * Modified by rmtodd@uokmax 6-28-87 -- when making an already existing dir,
  3594.  * subroutine didn't return EEXIST.  It does now.
  3595.  */
  3596.  
  3597. /*
  3598.  * Make a directory.
  3599.  */
  3600. #ifdef MKDIR_PROTOTYPE
  3601. MKDIR_PROTOTYPE
  3602. #else
  3603. int
  3604. mkdir (CONST char *dpath, int dmode)
  3605. #endif
  3606. {
  3607.   int cpid, status, fd;
  3608.   struct stat statbuf;
  3609.  
  3610.   if (stat (dpath, &statbuf) == 0)
  3611.     {
  3612.       errno = EEXIST;        /* Stat worked, so it already exists */
  3613.       return -1;
  3614.     }
  3615.  
  3616.   /* If stat fails for a reason other than non-existence, return error */
  3617.   if (errno != ENOENT)
  3618.     return -1;
  3619.  
  3620.   synch_process_alive = 1;
  3621.   switch (cpid = fork ())
  3622.     {
  3623.  
  3624.     case -1:            /* Error in fork() */
  3625.       return (-1);        /* Errno is set already */
  3626.  
  3627.     case 0:            /* Child process */
  3628.     {
  3629.       /*
  3630.          * Cheap hack to set mode of new directory.  Since this
  3631.          * child process is going away anyway, we zap its umask.
  3632.          * ####, this won't suffice to set SUID, SGID, etc. on this
  3633.          * directory.  Does anybody care?
  3634.          */
  3635.       status = umask (0);    /* Get current umask */
  3636.       status = umask (status | (0777 & ~dmode));    /* Set for mkdir */
  3637.       fd = sys_open ("/dev/null", 2);
  3638.       if (fd >= 0)
  3639.         {
  3640.       dup2 (fd, 0);
  3641.       dup2 (fd, 1);
  3642.       dup2 (fd, 2);
  3643.         }
  3644.       execl ("/bin/mkdir", "mkdir", dpath, (char *) 0);
  3645.       _exit (-1);        /* Can't exec /bin/mkdir */
  3646.     }
  3647.  
  3648.     default:            /* Parent process */
  3649.       wait_for_termination (cpid);
  3650.     }
  3651.  
  3652.   if (synch_process_death != 0 || synch_process_retcode != 0)
  3653.     {
  3654.       errno = EIO;        /* We don't know why, but */
  3655.       return -1;        /* /bin/mkdir failed */
  3656.     }
  3657.  
  3658.   return 0;
  3659. }
  3660. #endif /* not HAVE_MKDIR */
  3661.  
  3662. #ifndef HAVE_RMDIR
  3663. int
  3664. rmdir (CONST char *dpath)
  3665. {
  3666.   int cpid, status, fd;
  3667.   struct stat statbuf;
  3668.  
  3669.   if (stat (dpath, &statbuf) != 0)
  3670.     {
  3671.       /* Stat just set errno.  We don't have to */
  3672.       return -1;
  3673.     }
  3674.  
  3675.   synch_process_alive = 1;
  3676.   switch (cpid = fork ())
  3677.     {
  3678.  
  3679.     case -1:            /* Error in fork() */
  3680.       return (-1);        /* Errno is set already */
  3681.  
  3682.     case 0:            /* Child process */
  3683.       fd = sys_open("/dev/null", 2);
  3684.       if (fd >= 0)
  3685.         {
  3686.       dup2 (fd, 0);
  3687.       dup2 (fd, 1);
  3688.       dup2 (fd, 2);
  3689.         }
  3690.       execl ("/bin/rmdir", "rmdir", dpath, (char *) 0);
  3691.       _exit (-1);        /* Can't exec /bin/mkdir */
  3692.  
  3693.     default:            /* Parent process */
  3694.       wait_for_termination (cpid);
  3695.     }
  3696.  
  3697.   if (synch_process_death != 0 || synch_process_retcode != 0)
  3698.     {
  3699.       errno = EIO;        /* We don't know why, but */
  3700.       return -1;        /* /bin/rmdir failed */
  3701.     }
  3702.  
  3703.   return 0;
  3704. }
  3705. #endif /* !HAVE_RMDIR */
  3706.  
  3707.  
  3708. /************************************************************************/
  3709. /*                     VMS emulation of system calls                    */
  3710. /************************************************************************/
  3711.  
  3712. #ifdef VMS
  3713. #include "vms-pwd.h"
  3714. #include <acldef.h>
  3715. #include <chpdef.h>
  3716. #include <jpidef.h>
  3717.  
  3718. /* Return as a string the VMS error string pertaining to STATUS.
  3719.    Reuses the same static buffer each time it is called.  */
  3720.  
  3721. char *
  3722. vmserrstr (int status)    /* VMS status code */
  3723. {
  3724.   int bufadr[2];
  3725.   short len;
  3726.   static char buf[257];
  3727.  
  3728.   bufadr[0] = sizeof buf - 1;
  3729.   bufadr[1] = (int) buf;
  3730.   if (! (SYS$GETMSG (status, &len, bufadr, 0x1, 0) & 1))
  3731.     return "untranslatable VMS error status";
  3732.   buf[len] = '\0';
  3733.   return buf;
  3734. }
  3735.  
  3736. #ifdef access
  3737. #undef access
  3738.   
  3739. /* The following is necessary because 'access' emulation by VMS C (2.0) does
  3740.  * not work correctly.  (It also doesn't work well in version 2.3.)
  3741.  */
  3742.  
  3743. #ifdef VMS4_4
  3744.  
  3745. #define DESCRIPTOR(name,string) struct dsc$descriptor_s name = \
  3746.     { strlen (string), DSC$K_DTYPE_T, DSC$K_CLASS_S, string }
  3747.  
  3748. typedef union {
  3749.     struct {
  3750.     unsigned short s_buflen;
  3751.     unsigned short s_code;
  3752.     char *s_bufadr;
  3753.     unsigned short *s_retlenadr;
  3754.     } s;
  3755.     int end;
  3756. } item;
  3757. #define buflen s.s_buflen
  3758. #define code s.s_code
  3759. #define bufadr s.s_bufadr
  3760. #define retlenadr s.s_retlenadr
  3761.  
  3762. #define R_OK 4    /* test for read permission */
  3763. #define W_OK 2    /* test for write permission */
  3764. #define X_OK 1    /* test for execute (search) permission */
  3765. #define F_OK 0    /* test for presence of file */
  3766.  
  3767. int
  3768. vms_access (CONST char *path, int mode)
  3769. {
  3770.   static char *user = NULL;
  3771.   char dir_fn[512];
  3772.  
  3773.   /* translate possible directory spec into .DIR file name, so brain-dead
  3774.    * access can treat the directory like a file.  */
  3775.   if (directory_file_name (path, dir_fn))
  3776.     path = dir_fn;
  3777.   
  3778.   if (mode == F_OK)
  3779.     return access (path, mode);
  3780.   if (user == NULL && (user = (char *) getenv ("USER")) == NULL)
  3781.     return -1;
  3782.   {
  3783.     int stat;
  3784.     int flags;
  3785.     int acces;
  3786.     unsigned short int dummy;
  3787.     item itemlst[3];
  3788.     static int constant = ACL$C_FILE;
  3789.     DESCRIPTOR (path_desc, path);
  3790.     DESCRIPTOR (user_desc, user);
  3791.  
  3792.     flags = 0;
  3793.     acces = 0;
  3794.     if ((mode & X_OK) && ((stat = access (path, mode)) < 0 || mode == X_OK))
  3795.       return stat;
  3796.     if (mode & R_OK)
  3797.       acces |= CHP$M_READ;
  3798.     if (mode & W_OK)
  3799.       acces |= CHP$M_WRITE;
  3800.     itemlst[0].buflen = sizeof (int);
  3801.     itemlst[0].code = CHP$_FLAGS;
  3802.     itemlst[0].bufadr = (char *) &flags;
  3803.     itemlst[0].retlenadr = &dummy;
  3804.     itemlst[1].buflen = sizeof (int);
  3805.     itemlst[1].code = CHP$_ACCESS;
  3806.     itemlst[1].bufadr = (char *) &acces;
  3807.     itemlst[1].retlenadr = &dummy;
  3808.     itemlst[2].end = CHP$_END;
  3809.     stat = SYS$CHECK_ACCESS (&constant, &path_desc, &user_desc, itemlst);
  3810.     return stat == SS$_NORMAL ? 0 : -1;
  3811.   }
  3812. }
  3813.  
  3814. #else /* not VMS4_4 */
  3815.  
  3816. #include <prvdef.h>
  3817. #define    ACE$M_WRITE    2
  3818. #define    ACE$C_KEYID    1
  3819.  
  3820. static unsigned short vms_memid, vms_grpid;
  3821. static unsigned int vms_uic;
  3822.  
  3823. /* Called from init_sys_modes, so it happens not very often
  3824.    but at least each time Emacs is loaded.  */
  3825. sys_access_reinit (void)
  3826. {
  3827.   vms_uic = 0;
  3828. }
  3829.  
  3830. int
  3831. vms_access (CONST char *filename, int type)
  3832. {
  3833.   struct FAB fab;
  3834.   struct XABPRO xab;
  3835.   int status, size, i, typecode, acl_controlled;
  3836.   unsigned int *aclptr, *aclend, aclbuf[60];
  3837.   union prvdef prvmask;
  3838.  
  3839.   /* Get UIC and GRP values for protection checking.  */
  3840.   if (vms_uic == 0)
  3841.     {
  3842.       status = LIB$GETJPI (&JPI$_UIC, 0, 0, &vms_uic, 0, 0);
  3843.       if (! (status & 1))
  3844.     return -1;
  3845.       vms_memid = vms_uic & 0xFFFF;
  3846.       vms_grpid = vms_uic >> 16;
  3847.     }
  3848.  
  3849.   if (type != 2)        /* not checking write access */
  3850.     return access (filename, type);
  3851.  
  3852.   /* Check write protection. */
  3853.     
  3854. #define    CHECKPRIV(bit)    (prvmask.bit)
  3855. #define    WRITEABLE(field)  (! ((xab.xab$w_pro >> field) & XAB$M_NOWRITE))
  3856.  
  3857.   /* Find privilege bits */
  3858.   status = SYS$SETPRV (0, 0, 0, prvmask);
  3859.   if (! (status & 1))
  3860.     error ("Unable to find privileges: %s", vmserrstr (status));
  3861.   if (CHECKPRIV (PRV$V_BYPASS))
  3862.     return 0;            /* BYPASS enabled */
  3863.   fab = cc$rms_fab;
  3864.   fab.fab$b_fac = FAB$M_GET;
  3865.   fab.fab$l_fna = filename;
  3866.   fab.fab$b_fns = strlen (filename);
  3867.   fab.fab$l_xab = &xab;
  3868.   xab = cc$rms_xabpro;
  3869.   xab.xab$l_aclbuf = aclbuf;
  3870.   xab.xab$w_aclsiz = sizeof (aclbuf);
  3871.   status = SYS$OPEN (&fab, 0, 0);
  3872.   if (! (status & 1))
  3873.     return -1;
  3874.   SYS$CLOSE (&fab, 0, 0);
  3875.   /* Check system access */
  3876.   if (CHECKPRIV (PRV$V_SYSPRV) && WRITEABLE (XAB$V_SYS))
  3877.     return 0;
  3878.   /* Check ACL entries, if any */
  3879.   acl_controlled = 0;
  3880.   if (xab.xab$w_acllen > 0)
  3881.     {
  3882.       aclptr = aclbuf;
  3883.       aclend = &aclbuf[xab.xab$w_acllen / 4];
  3884.       while (*aclptr && aclptr < aclend)
  3885.     {
  3886.       size = (*aclptr & 0xff) / 4;
  3887.       typecode = (*aclptr >> 8) & 0xff;
  3888.       if (typecode == ACE$C_KEYID)
  3889.         for (i = size - 1; i > 1; i--)
  3890.           if (aclptr[i] == vms_uic)
  3891.         {
  3892.           acl_controlled = 1;
  3893.           if (aclptr[1] & ACE$M_WRITE)
  3894.             return 0;    /* Write access through ACL */
  3895.         }
  3896.       aclptr = &aclptr[size];
  3897.     }
  3898.       if (acl_controlled)    /* ACL specified, prohibits write access */
  3899.     return -1;
  3900.     }
  3901.   /* No ACL entries specified, check normal protection */
  3902.   if (WRITEABLE (XAB$V_WLD))    /* World writeable */
  3903.     return 0;
  3904.   if (WRITEABLE (XAB$V_GRP) &&
  3905.       (unsigned short) (xab.xab$l_uic >> 16) == vms_grpid)
  3906.     return 0;            /* Group writeable */
  3907.   if (WRITEABLE (XAB$V_OWN) &&
  3908.       (xab.xab$l_uic & 0xFFFF) == vms_memid)
  3909.     return 0;            /* Owner writeable */
  3910.  
  3911.   return -1;    /* Not writeable */
  3912. }
  3913. #endif /* not VMS4_4 */
  3914. #endif /* access */
  3915.   
  3916. static char vtbuf[NAM$C_MAXRSS+1];
  3917.  
  3918. /* translate a vms file spec to a unix path */
  3919. char *
  3920. sys_translate_vms (char *vfile)
  3921. {
  3922.   char * p;
  3923.   char * targ;
  3924.  
  3925.   if (!vfile)
  3926.     return 0;
  3927.  
  3928.   targ = vtbuf;
  3929.  
  3930.   /* leading device or logical name is a root directory */
  3931.   if (p = strchr (vfile, ':'))
  3932.     {
  3933.       *targ++ = '/';
  3934.       while (vfile < p)
  3935.     *targ++ = *vfile++;
  3936.       vfile++;
  3937.       *targ++ = '/';
  3938.     }
  3939.   p = vfile;
  3940.   if (*p == '[' || *p == '<')
  3941.     {
  3942.       while (*++vfile != *p + 2)
  3943.     switch (*vfile)
  3944.       {
  3945.       case '.':
  3946.         if (vfile[-1] == *p)
  3947.           *targ++ = '.';
  3948.         *targ++ = '/';
  3949.         break;
  3950.  
  3951.       case '-':
  3952.         *targ++ = '.';
  3953.         *targ++ = '.';
  3954.         break;
  3955.         
  3956.       default:
  3957.         *targ++ = *vfile;
  3958.         break;
  3959.       }
  3960.       vfile++;
  3961.       *targ++ = '/';
  3962.     }
  3963.   while (*vfile)
  3964.     *targ++ = *vfile++;
  3965.  
  3966.   return vtbuf;
  3967. }
  3968.  
  3969. static char utbuf[NAM$C_MAXRSS+1];
  3970.  
  3971. /* translate a unix path to a VMS file spec */
  3972. char *
  3973. sys_translate_unix (char *ufile)
  3974. {
  3975.   int slash_seen = 0;
  3976.   char *p;
  3977.   char * targ;
  3978.  
  3979.   if (!ufile)
  3980.     return 0;
  3981.  
  3982.   targ = utbuf;
  3983.  
  3984.   if (*ufile == '/')
  3985.     {
  3986.       ufile++;
  3987.     }
  3988.  
  3989.   while (*ufile)
  3990.     {
  3991.       switch (*ufile)
  3992.     {
  3993.     case '/':
  3994.       if (slash_seen)
  3995.         if (strchr (&ufile[1], '/'))
  3996.           *targ++ = '.';
  3997.         else
  3998.           *targ++ = ']';
  3999.       else
  4000.         {
  4001.           *targ++ = ':';
  4002.           if (strchr (&ufile[1], '/'))
  4003.         *targ++ = '[';
  4004.           slash_seen = 1;
  4005.         }
  4006.       break;
  4007.  
  4008.     case '.':
  4009.       if (strncmp (ufile, "./", 2) == 0)
  4010.         {
  4011.           if (!slash_seen)
  4012.         {
  4013.           *targ++ = '[';
  4014.           slash_seen = 1;
  4015.         }
  4016.           ufile++;        /* skip the dot */
  4017.           if (strchr (&ufile[1], '/'))
  4018.         *targ++ = '.';
  4019.           else
  4020.         *targ++ = ']';
  4021.         }
  4022.       else if (strncmp (ufile, "../", 3) == 0)
  4023.         {
  4024.           if (!slash_seen)
  4025.         {
  4026.           *targ++ = '[';
  4027.           slash_seen = 1;
  4028.         }
  4029.           *targ++ = '-';
  4030.           ufile += 2;    /* skip the dots */
  4031.           if (strchr (&ufile[1], '/'))
  4032.         *targ++ = '.';
  4033.           else
  4034.         *targ++ = ']';
  4035.         }
  4036.       else
  4037.         *targ++ = *ufile;
  4038.       break;
  4039.  
  4040.     default:
  4041.       *targ++ = *ufile;
  4042.       break;
  4043.     }
  4044.       ufile++;
  4045.     }
  4046.   *targ = '\0';
  4047.   
  4048.   return utbuf;
  4049. }
  4050.  
  4051. char *
  4052. getwd (char *pathname)
  4053. {
  4054.   char *ptr;
  4055.   strcpy (pathname, egetenv ("PATH"));
  4056.  
  4057.   ptr = pathname;
  4058.   while (*ptr)
  4059.     {
  4060.       /* #### This is evil.  Smashes (shared) result of egetenv */
  4061.       *ptr = toupper (* (unsigned char *) ptr);
  4062.       ptr++;
  4063.     }
  4064.   return pathname;
  4065. }
  4066.  
  4067. int
  4068. getppid (void)
  4069. {
  4070.   long item_code = JPI$_OWNER;
  4071.   unsigned long parent_id;
  4072.   int status;
  4073.  
  4074.   if (((status = LIB$GETJPI (&item_code, 0, 0, &parent_id)) & 1) == 0)
  4075.     {
  4076.       errno = EVMSERR;
  4077.       vaxc$errno = status;
  4078.       return -1;
  4079.     }
  4080.   return parent_id;
  4081. }
  4082.  
  4083. #undef getuid
  4084. unsigned int
  4085. sys_getuid (void)
  4086. {
  4087.   return (getgid () << 16) | getuid ();
  4088. }
  4089.  
  4090. int
  4091. vms_read (int fildes, CONST void *buf, unsigned int nbyte)
  4092. {
  4093.   return read (fildes, buf, (nbyte < MAXIOSIZE ? nbyte : MAXIOSIZE));
  4094. }
  4095.  
  4096. #if 0
  4097. int
  4098. vms_write (int fildes, CONST void *buf, unsigned int nbyte)
  4099. {
  4100.   int nwrote, rtnval = 0;
  4101.  
  4102.   while (nbyte > MAXIOSIZE && (nwrote = write (fildes, buf, MAXIOSIZE)) > 0)
  4103.     {
  4104.       nbyte -= nwrote;
  4105.       buf += nwrote;
  4106.       rtnval += nwrote;
  4107.     }
  4108.   if (nwrote < 0)
  4109.     return rtnval ? rtnval : -1;
  4110.   if ((nwrote = write (fildes, buf, nbyte)) < 0)
  4111.     return rtnval ? rtnval : -1;
  4112.   return (rtnval + nwrote);
  4113. }
  4114. #endif /* 0 */
  4115.  
  4116. /*
  4117.  *    VAX/VMS VAX C RTL really loses. It insists that records
  4118.  *      end with a newline (carriage return) character, and if they
  4119.  *    don't it adds one (nice of it isn't it!)
  4120.  *
  4121.  *    Thus we do this stupidity below.
  4122.  */
  4123.  
  4124. int
  4125. vms_write (int fildes, CONST void *buf, unsigned int nbytes)
  4126. {
  4127.   char *p;
  4128.   char *e;
  4129.   int sum = 0;
  4130.   struct stat st;
  4131.  
  4132.   fstat (fildes, &st);
  4133.   p = buf;
  4134.   while (nbytes > 0)
  4135.     {
  4136.       int len, retval;
  4137.  
  4138.       /* Handle fixed-length files with carriage control.  */
  4139.       if (st.st_fab_rfm == FAB$C_FIX
  4140.       && ((st.st_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
  4141.     {
  4142.       len = st.st_fab_mrs;
  4143.       retval = write (fildes, p, min (len, nbytes));
  4144.       if (retval != len)
  4145.         return -1;
  4146.       retval++;    /* This skips the implied carriage control */
  4147.     }
  4148.       else
  4149.     {
  4150.       e =  p + min (MAXIOSIZE, nbytes) - 1;
  4151.       while (*e != '\n' && e > p) e--;
  4152.       if (p == e)        /* Ok.. so here we add a newline... sigh. */
  4153.         e = p + min (MAXIOSIZE, nbytes) - 1;
  4154.       len = e + 1 - p;
  4155.       retval = write (fildes, p, len);
  4156.       if (retval != len)
  4157.         return -1;
  4158.     }
  4159.       p += retval;
  4160.       sum += retval;
  4161.       nbytes -= retval;
  4162.     }
  4163.   return sum;
  4164. }
  4165.  
  4166. /* Create file NEW copying its attributes from file OLD.  If
  4167.    OLD is 0 or does not exist, create based on the value of
  4168.    vms_stmlf_recfm. */
  4169.  
  4170. /* Protection value the file should ultimately have.
  4171.    Set by create_copy_attrs, and use by rename_sansversions.  */
  4172. static unsigned short int vms_fab_final_pro;
  4173.  
  4174. int
  4175. creat_copy_attrs (char *old, char *new)
  4176. {
  4177.   struct FAB fab = cc$rms_fab;
  4178.   struct XABPRO xabpro;
  4179.   char aclbuf[256];    /* Choice of size is arbitrary.  See below. */
  4180.   extern int vms_stmlf_recfm;
  4181.  
  4182.   if (old)
  4183.     {
  4184.       fab.fab$b_fac = FAB$M_GET;
  4185.       fab.fab$l_fna = old;
  4186.       fab.fab$b_fns = strlen (old);
  4187.       fab.fab$l_xab = (char *) &xabpro;
  4188.       xabpro = cc$rms_xabpro;
  4189.       xabpro.xab$l_aclbuf = aclbuf;
  4190.       xabpro.xab$w_aclsiz = sizeof aclbuf;
  4191.       /* Call $OPEN to fill in the fab & xabpro fields. */
  4192.       if (SYS$OPEN (&fab, 0, 0) & 1)
  4193.     {
  4194.       SYS$CLOSE (&fab, 0, 0);
  4195.       fab.fab$l_alq = 0;    /* zero the allocation quantity */
  4196.       if (xabpro.xab$w_acllen > 0)
  4197.         {
  4198.           if (xabpro.xab$w_acllen > sizeof aclbuf)
  4199.         /* If the acl buffer was too short, redo open with longer one.
  4200.            Wouldn't need to do this if there were some system imposed
  4201.            limit on the size of an ACL, but I can't find any such. */
  4202.         {
  4203.           xabpro.xab$l_aclbuf = (char *) alloca (xabpro.xab$w_acllen);
  4204.           xabpro.xab$w_aclsiz = xabpro.xab$w_acllen;
  4205.           if (SYS$OPEN (&fab, 0, 0) & 1)
  4206.             SYS$CLOSE (&fab, 0, 0);
  4207.           else
  4208.             old = 0;
  4209.         }
  4210.         }
  4211.       else
  4212.         xabpro.xab$l_aclbuf = 0;
  4213.     }
  4214.       else
  4215.     old = 0;
  4216.     }
  4217.   fab.fab$l_fna = new;
  4218.   fab.fab$b_fns = strlen (new);
  4219.   if (!old)
  4220.     {
  4221.       fab.fab$l_xab = 0;
  4222.       fab.fab$b_rfm = vms_stmlf_recfm ? FAB$C_STMLF : FAB$C_VAR;
  4223.       fab.fab$b_rat = FAB$M_CR;
  4224.     }
  4225.  
  4226.   /* Set the file protections such that we will be able to manipulate
  4227.      this file.  Once we are done writing and renaming it, we will set
  4228.      the protections back.  */
  4229.   if (old)
  4230.     vms_fab_final_pro = xabpro.xab$w_pro;
  4231.   else
  4232.     SYS$SETDFPROT (0, &vms_fab_final_pro);
  4233.   xabpro.xab$w_pro &= 0xff0f; /* set O:rewd for now. This is set back later. */
  4234.  
  4235.   /* Create the new file with either default attrs or attrs copied
  4236.      from old file. */
  4237.   if (!(SYS$CREATE (&fab, 0, 0) & 1))
  4238.     return -1;
  4239.   SYS$CLOSE (&fab, 0, 0);
  4240.   /* As this is a "replacement" for creat, return a file descriptor
  4241.      opened for writing. */
  4242.   return open (new, O_WRONLY);
  4243. }
  4244.  
  4245. int
  4246. vms_creat (CONST char *path, int mode, ...)
  4247. {
  4248.   int rfd;            /* related file descriptor */
  4249.   int fd;            /* Our new file descriptor */
  4250.   int count;
  4251.   struct stat st_buf;
  4252.   char rfm[12];
  4253.   char rat[15];
  4254.   char mrs[13];
  4255.   char fsz[13];
  4256.   extern int vms_stmlf_recfm;
  4257.  
  4258.   /* #### there was some weird machine-dependent code to determine how many
  4259.      arguments were passed to this function.  This certainly won't work
  4260.      under ANSI C. */
  4261.   if (count > 2)
  4262.     rfd = fix this;
  4263.   if (count > 2)
  4264.     {
  4265.       /* Use information from the related file descriptor to set record
  4266.      format of the newly created file. */
  4267.       fstat (rfd, &st_buf);
  4268.       switch (st_buf.st_fab_rfm)
  4269.     {
  4270.     case FAB$C_FIX:
  4271.       strcpy (rfm, "rfm = fix");
  4272.       sprintf (mrs, "mrs = %d", st_buf.st_fab_mrs);
  4273.       strcpy (rat, "rat = ");
  4274.       if (st_buf.st_fab_rat & FAB$M_CR)
  4275.         strcat (rat, "cr");
  4276.       else if (st_buf.st_fab_rat & FAB$M_FTN)
  4277.         strcat (rat, "ftn");
  4278.       else if (st_buf.st_fab_rat & FAB$M_PRN)
  4279.         strcat (rat, "prn");
  4280.       if (st_buf.st_fab_rat & FAB$M_BLK)
  4281.         if (st_buf.st_fab_rat & (FAB$M_CR|FAB$M_FTN|FAB$M_PRN))
  4282.           strcat (rat, ", blk");
  4283.         else
  4284.           strcat (rat, "blk");
  4285.       return creat (name, 0, rfm, rat, mrs);
  4286.  
  4287.     case FAB$C_VFC:
  4288.       strcpy (rfm, "rfm = vfc");
  4289.       sprintf (fsz, "fsz = %d", st_buf.st_fab_fsz);
  4290.       strcpy (rat, "rat = ");
  4291.       if (st_buf.st_fab_rat & FAB$M_CR)
  4292.         strcat (rat, "cr");
  4293.       else if (st_buf.st_fab_rat & FAB$M_FTN)
  4294.         strcat (rat, "ftn");
  4295.       else if (st_buf.st_fab_rat & FAB$M_PRN)
  4296.         strcat (rat, "prn");
  4297.       if (st_buf.st_fab_rat & FAB$M_BLK)
  4298.         if (st_buf.st_fab_rat & (FAB$M_CR|FAB$M_FTN|FAB$M_PRN))
  4299.           strcat (rat, ", blk");
  4300.         else
  4301.           strcat (rat, "blk");
  4302.       return creat (name, 0, rfm, rat, fsz);
  4303.  
  4304.     case FAB$C_STM:
  4305.       strcpy (rfm, "rfm = stm");
  4306.       break;
  4307.  
  4308.     case FAB$C_STMCR:
  4309.       strcpy (rfm, "rfm = stmcr");
  4310.       break;
  4311.  
  4312.     case FAB$C_STMLF:
  4313.       strcpy (rfm, "rfm = stmlf");
  4314.       break;
  4315.  
  4316.     case FAB$C_UDF:
  4317.       strcpy (rfm, "rfm = udf");
  4318.       break;
  4319.  
  4320.     case FAB$C_VAR:
  4321.       strcpy (rfm, "rfm = var");
  4322.       break;
  4323.     }
  4324.       strcpy (rat, "rat = ");
  4325.       if (st_buf.st_fab_rat & FAB$M_CR)
  4326.     strcat (rat, "cr");
  4327.       else if (st_buf.st_fab_rat & FAB$M_FTN)
  4328.     strcat (rat, "ftn");
  4329.       else if (st_buf.st_fab_rat & FAB$M_PRN)
  4330.     strcat (rat, "prn");
  4331.       if (st_buf.st_fab_rat & FAB$M_BLK)
  4332.     if (st_buf.st_fab_rat & (FAB$M_CR|FAB$M_FTN|FAB$M_PRN))
  4333.       strcat (rat, ", blk");
  4334.     else
  4335.       strcat (rat, "blk");
  4336.     }
  4337.   else
  4338.     {
  4339.       strcpy (rfm, vms_stmlf_recfm ? "rfm = stmlf" : "rfm=var");
  4340.       strcpy (rat, "rat=cr");
  4341.     }
  4342.   /* Until the VAX C RTL fixes the many bugs with modes, always use
  4343.      mode 0 to get the user's default protection. */
  4344.   fd = creat (name, 0, rfm, rat);
  4345.   if (fd < 0 && errno == EEXIST)
  4346.     {
  4347.       if (unlink (name) < 0)
  4348.     report_file_error ("delete", build_string (name));
  4349.       fd = creat (name, 0, rfm, rat);
  4350.     }
  4351.   return fd;
  4352. }
  4353.  
  4354. /* fwrite to stdout is S L O W.  Speed it up by using fputc...*/
  4355. int
  4356. vms_fwrite (CONST void *ptr, int size, int num, FILE *fp)
  4357. {
  4358.   int tot = num * size;
  4359.  
  4360.   while (tot--)
  4361.     fputc (* (CONST char *) ptr++, fp);
  4362.   return (num);
  4363. }
  4364.  
  4365. /*
  4366.  * The VMS C library routine creat actually creates a new version of an
  4367.  * existing file rather than truncating the old version.  There are times
  4368.  * when this is not the desired behavior, for instance, when writing an
  4369.  * auto save file (you only want one version), or when you don't have
  4370.  * write permission in the directory containing the file (but the file
  4371.  * itself is writable).  Hence this routine, which is equivalent to 
  4372.  * "close (creat (fn, 0));" on Unix if fn already exists.
  4373.  */
  4374. int
  4375. vms_truncate (char *fn)
  4376. {
  4377.   struct FAB xfab = cc$rms_fab;
  4378.   struct RAB xrab = cc$rms_rab;
  4379.   int status;
  4380.  
  4381.   xfab.fab$l_fop = FAB$M_TEF;    /* free allocated but unused blocks on close */
  4382.   xfab.fab$b_fac = FAB$M_TRN | FAB$M_GET; /* allow truncate and get access */
  4383.   xfab.fab$b_shr = FAB$M_NIL;    /* allow no sharing - file must be locked */
  4384.   xfab.fab$l_fna = fn;
  4385.   xfab.fab$b_fns = strlen (fn);
  4386.   xfab.fab$l_dna = ";0";    /* default to latest version of the file */
  4387.   xfab.fab$b_dns = 2;
  4388.   xrab.rab$l_fab = &xfab;
  4389.  
  4390.   /* This gibberish opens the file, positions to the first record, and
  4391.      deletes all records from there until the end of file. */
  4392.   if ((SYS$OPEN (&xfab) & 01) == 01)
  4393.     {
  4394.       if ((SYS$CONNECT (&xrab) & 01) == 01 &&
  4395.       (SYS$FIND (&xrab) & 01) == 01 &&
  4396.       (SYS$TRUNCATE (&xrab) & 01) == 01)
  4397.     status = 0;
  4398.       else
  4399.     status = -1;
  4400.     }
  4401.   else
  4402.     status = -1;
  4403.   SYS$CLOSE (&xfab);
  4404.   return status;
  4405. }
  4406.  
  4407. /* Define this symbol to actually read SYSUAF.DAT.  This requires either
  4408.    SYSPRV or a readable SYSUAF.DAT. */
  4409.  
  4410. #ifdef READ_SYSUAF
  4411. /*
  4412.  * getuaf.c
  4413.  *
  4414.  * Routine to read the VMS User Authorization File and return
  4415.  * a specific user's record.
  4416.  */
  4417.  
  4418. static struct UAF vms_retuaf;
  4419.  
  4420. static struct UAF *
  4421. get_uaf_name (char *uname)
  4422. {
  4423.   status;
  4424.   struct FAB uaf_fab;
  4425.   struct RAB uaf_rab;
  4426.   
  4427.   uaf_fab = cc$rms_fab;
  4428.   uaf_rab = cc$rms_rab;
  4429.   /* initialize fab fields */
  4430.   uaf_fab.fab$l_fna = "SYS$SYSTEM:SYSUAF.DAT";
  4431.   uaf_fab.fab$b_fns = 21;
  4432.   uaf_fab.fab$b_fac = FAB$M_GET;
  4433.   uaf_fab.fab$b_org = FAB$C_IDX;
  4434.   uaf_fab.fab$b_shr = FAB$M_GET|FAB$M_PUT|FAB$M_UPD|FAB$M_DEL;
  4435.   /* initialize rab fields */
  4436.   uaf_rab.rab$l_fab = &uaf_fab;
  4437.   /* open the User Authorization File */
  4438.   status = SYS$OPEN (&uaf_fab);
  4439.   if (!(status&1))
  4440.     {
  4441.       errno = EVMSERR;
  4442.       vaxc$errno = status;
  4443.       return 0;
  4444.     }
  4445.   status = SYS$CONNECT (&uaf_rab);
  4446.   if (!(status&1))
  4447.     {
  4448.       errno = EVMSERR;
  4449.       vaxc$errno = status;
  4450.       return 0;
  4451.     }
  4452.   /* read the requested record - index is in uname */
  4453.   uaf_rab.rab$l_kbf = uname;
  4454.   uaf_rab.rab$b_ksz = strlen (uname);
  4455.   uaf_rab.rab$b_rac = RAB$C_KEY;
  4456.   uaf_rab.rab$l_ubf = (char *)&vms_retuaf;
  4457.   uaf_rab.rab$w_usz = sizeof vms_retuaf;
  4458.   status = SYS$GET (&uaf_rab);
  4459.   if (!(status&1))
  4460.     {
  4461.       errno = EVMSERR;
  4462.       vaxc$errno = status;
  4463.       return 0;
  4464.     }
  4465.   /* close the User Authorization File */
  4466.   status = SYS$DISCONNECT (&uaf_rab);
  4467.   if (!(status&1))
  4468.     {
  4469.       errno = EVMSERR;
  4470.       vaxc$errno = status;
  4471.       return 0;
  4472.     }
  4473.   status = SYS$CLOSE (&uaf_fab);
  4474.   if (!(status&1))
  4475.     {
  4476.       errno = EVMSERR;
  4477.       vaxc$errno = status;
  4478.       return 0;
  4479.     }
  4480.   return &vms_retuaf;
  4481. }
  4482.  
  4483. static struct UAF *
  4484. get_uaf_uic (unsigned long uic)
  4485. {
  4486.   status;
  4487.   struct FAB uaf_fab;
  4488.   struct RAB uaf_rab;
  4489.   
  4490.   uaf_fab = cc$rms_fab;
  4491.   uaf_rab = cc$rms_rab;
  4492.   /* initialize fab fields */
  4493.   uaf_fab.fab$l_fna = "SYS$SYSTEM:SYSUAF.DAT";
  4494.   uaf_fab.fab$b_fns = 21;
  4495.   uaf_fab.fab$b_fac = FAB$M_GET;
  4496.   uaf_fab.fab$b_org = FAB$C_IDX;
  4497.   uaf_fab.fab$b_shr = FAB$M_GET|FAB$M_PUT|FAB$M_UPD|FAB$M_DEL;
  4498.   /* initialize rab fields */
  4499.   uaf_rab.rab$l_fab = &uaf_fab;
  4500.   /* open the User Authorization File */
  4501.   status = SYS$OPEN (&uaf_fab);
  4502.   if (!(status&1))
  4503.     {
  4504.       errno = EVMSERR;
  4505.       vaxc$errno = status;
  4506.       return 0;
  4507.     }
  4508.   status = SYS$CONNECT (&uaf_rab);
  4509.   if (!(status&1))
  4510.     {
  4511.       errno = EVMSERR;
  4512.       vaxc$errno = status;
  4513.       return 0;
  4514.     }
  4515.   /* read the requested record - index is in uic */
  4516.   uaf_rab.rab$b_krf = 1;    /* 1st alternate key */
  4517.   uaf_rab.rab$l_kbf = (char *) &uic;
  4518.   uaf_rab.rab$b_ksz = sizeof uic;
  4519.   uaf_rab.rab$b_rac = RAB$C_KEY;
  4520.   uaf_rab.rab$l_ubf = (char *)&vms_retuaf;
  4521.   uaf_rab.rab$w_usz = sizeof vms_retuaf;
  4522.   status = SYS$GET (&uaf_rab);
  4523.   if (!(status&1))
  4524.     {
  4525.       errno = EVMSERR;
  4526.       vaxc$errno = status;
  4527.       return 0;
  4528.     }
  4529.   /* close the User Authorization File */
  4530.   status = SYS$DISCONNECT (&uaf_rab);
  4531.   if (!(status&1))
  4532.     {
  4533.       errno = EVMSERR;
  4534.       vaxc$errno = status;
  4535.       return 0;
  4536.     }
  4537.   status = SYS$CLOSE (&uaf_fab);
  4538.   if (!(status&1))
  4539.     {
  4540.       errno = EVMSERR;
  4541.       vaxc$errno = status;
  4542.       return 0;
  4543.     }
  4544.   return &vms_retuaf;
  4545. }
  4546.  
  4547. static struct passwd vms_retpw;
  4548.  
  4549. static struct passwd *
  4550. cnv_uaf_pw (struct UAF *up)
  4551. {
  4552.   char * ptr;
  4553.  
  4554.   /* copy these out first because if the username is 32 chars, the next
  4555.      section will overwrite the first byte of the UIC */
  4556.   vms_retpw.pw_uid = up->uaf$w_mem;
  4557.   vms_retpw.pw_gid = up->uaf$w_grp;
  4558.  
  4559.   /* I suppose this is not the best sytle, to possibly overwrite one
  4560.      byte beyond the end of the field, but what the heck... */
  4561.   ptr = &up->uaf$t_username[UAF$S_USERNAME];
  4562.   while (ptr[-1] == ' ')
  4563.     ptr--;
  4564.   *ptr = '\0';
  4565.   strcpy (vms_retpw.pw_name, up->uaf$t_username);
  4566.  
  4567.   /* the rest of these are counted ascii strings */
  4568.   strncpy (vms_retpw.pw_gecos, &up->uaf$t_owner[1], up->uaf$t_owner[0]);
  4569.   vms_retpw.pw_gecos[up->uaf$t_owner[0]] = '\0';
  4570.   strncpy (vms_retpw.pw_dir, &up->uaf$t_defdev[1], up->uaf$t_defdev[0]);
  4571.   vms_retpw.pw_dir[up->uaf$t_defdev[0]] = '\0';
  4572.   strncat (vms_retpw.pw_dir, &up->uaf$t_defdir[1], up->uaf$t_defdir[0]);
  4573.   vms_retpw.pw_dir[up->uaf$t_defdev[0] + up->uaf$t_defdir[0]] = '\0';
  4574.   strncpy (vms_retpw.pw_shell, &up->uaf$t_defcli[1], up->uaf$t_defcli[0]);
  4575.   vms_retpw.pw_shell[up->uaf$t_defcli[0]] = '\0';
  4576.  
  4577.   return &vms_retpw;
  4578. }
  4579. #else /* not READ_SYSUAF */
  4580. static struct passwd vms_retpw;
  4581. #endif /* not READ_SYSUAF */
  4582.  
  4583. struct passwd *
  4584. getpwnam (char *name)
  4585. {
  4586. #ifdef READ_SYSUAF
  4587.   struct UAF *up;
  4588. #else
  4589.   char * user;
  4590.   char * dir;
  4591.   unsigned char * full;
  4592. #endif /* READ_SYSUAF */
  4593.   char *ptr = name;
  4594.  
  4595.   while (*ptr)
  4596.     {
  4597.       *ptr = toupper (* (unsigned char *) ptr);
  4598.       ptr++;
  4599.     }
  4600. #ifdef READ_SYSUAF
  4601.   if (!(up = get_uaf_name (name)))
  4602.     return 0;
  4603.   return cnv_uaf_pw (up);
  4604. #else
  4605.   if (strcmp (name, getenv ("USER")) == 0)
  4606.     {
  4607.       vms_retpw.pw_uid = getuid ();
  4608.       vms_retpw.pw_gid = getgid ();
  4609.       strcpy (vms_retpw.pw_name, name);
  4610.       if (full = egetenv ("FULLNAME"))
  4611.     strcpy (vms_retpw.pw_gecos, full);
  4612.       else
  4613.     *vms_retpw.pw_gecos = '\0';
  4614.       strcpy (vms_retpw.pw_dir, egetenv ("HOME"));
  4615.       *vms_retpw.pw_shell = '\0';
  4616.       return &vms_retpw;
  4617.     }
  4618.   else
  4619.     return 0;
  4620. #endif /* not READ_SYSUAF */
  4621. }
  4622.  
  4623. struct passwd *
  4624. getpwuid (unsigned long uid)
  4625. {
  4626. #ifdef READ_SYSUAF
  4627.   struct UAF * up;
  4628.  
  4629.   if (!(up = get_uaf_uic (uid)))
  4630.     return 0;
  4631.   return cnv_uaf_pw (up);
  4632. #else
  4633.   if (uid == sys_getuid ())
  4634.     return getpwnam (egetenv ("USER"));
  4635.   else
  4636.     return 0;
  4637. #endif /* not READ_SYSUAF */
  4638. }
  4639.  
  4640. /* return total address space available to the current process.  This is
  4641.    the sum of the current p0 size, p1 size and free page table entries
  4642.    available. */
  4643. int
  4644. vlimit (void)
  4645. {
  4646.   int item_code;
  4647.   unsigned long free_pages;
  4648.   unsigned long frep0va;
  4649.   unsigned long frep1va;
  4650.   status;
  4651.  
  4652.   item_code = JPI$_FREPTECNT;
  4653.   if (((status = LIB$GETJPI (&item_code, 0, 0, &free_pages)) & 1) == 0)
  4654.     {
  4655.       errno = EVMSERR;
  4656.       vaxc$errno = status;
  4657.       return -1;
  4658.     }
  4659.   free_pages *= 512;
  4660.  
  4661.   item_code = JPI$_FREP0VA;
  4662.   if (((status = LIB$GETJPI (&item_code, 0, 0, &frep0va)) & 1) == 0)
  4663.     {
  4664.       errno = EVMSERR;
  4665.       vaxc$errno = status;
  4666.       return -1;
  4667.     }
  4668.   item_code = JPI$_FREP1VA;
  4669.   if (((status = LIB$GETJPI (&item_code, 0, 0, &frep1va)) & 1) == 0)
  4670.     {
  4671.       errno = EVMSERR;
  4672.       vaxc$errno = status;
  4673.       return -1;
  4674.     }
  4675.  
  4676.   return free_pages + frep0va + (0x7fffffff - frep1va);
  4677. }
  4678.  
  4679. int
  4680. define_logical_name (char *varname, char *string)
  4681. {
  4682.   struct dsc$descriptor_s strdsc =
  4683.     {strlen (string), DSC$K_DTYPE_T, DSC$K_CLASS_S, string};
  4684.   struct dsc$descriptor_s envdsc =
  4685.     {strlen (varname), DSC$K_DTYPE_T, DSC$K_CLASS_S, varname};
  4686.   struct dsc$descriptor_s lnmdsc =
  4687.     {7, DSC$K_DTYPE_T, DSC$K_CLASS_S, "LNM$JOB"};
  4688.  
  4689.   return LIB$SET_LOGICAL (&envdsc, &strdsc, &lnmdsc, 0, 0);
  4690. }
  4691.  
  4692. int
  4693. delete_logical_name (char *varname)
  4694. {
  4695.   struct dsc$descriptor_s envdsc =
  4696.     {strlen (varname), DSC$K_DTYPE_T, DSC$K_CLASS_S, varname};
  4697.   struct dsc$descriptor_s lnmdsc =
  4698.     {7, DSC$K_DTYPE_T, DSC$K_CLASS_S, "LNM$JOB"};
  4699.  
  4700.   return LIB$DELETE_LOGICAL (&envdsc, &lnmdsc);
  4701. }
  4702.  
  4703. execvp (void)
  4704. {
  4705.   error ("execvp system call not implemented");
  4706. }
  4707.  
  4708. int
  4709. rename (char *from, char *to)
  4710. {
  4711.   int status;
  4712.   struct FAB from_fab = cc$rms_fab, to_fab = cc$rms_fab;
  4713.   struct NAM from_nam = cc$rms_nam, to_nam = cc$rms_nam;
  4714.   char from_esn[NAM$C_MAXRSS];
  4715.   char to_esn[NAM$C_MAXRSS];
  4716.  
  4717.   from_fab.fab$l_fna = from;
  4718.   from_fab.fab$b_fns = strlen (from);
  4719.   from_fab.fab$l_nam = &from_nam;
  4720.   from_fab.fab$l_fop = FAB$M_NAM;
  4721.  
  4722.   from_nam.nam$l_esa = from_esn;
  4723.   from_nam.nam$b_ess = sizeof from_esn;
  4724.  
  4725.   to_fab.fab$l_fna = to;
  4726.   to_fab.fab$b_fns = strlen (to);
  4727.   to_fab.fab$l_nam = &to_nam;
  4728.   to_fab.fab$l_fop = FAB$M_NAM;
  4729.  
  4730.   to_nam.nam$l_esa = to_esn;
  4731.   to_nam.nam$b_ess = sizeof to_esn;
  4732.  
  4733.   status = SYS$RENAME (&from_fab, 0, 0, &to_fab);
  4734.  
  4735.   if (status & 1)
  4736.     return 0;
  4737.   else
  4738.     {
  4739.       if (status == RMS$_DEV)
  4740.     errno = EXDEV;
  4741.       else
  4742.     errno = EVMSERR;
  4743.       vaxc$errno = status;
  4744.       return -1;
  4745.     }
  4746. }
  4747.  
  4748. /* This function renames a file like `rename', but it strips
  4749.    the version number from the "to" filename, such that the "to" file is
  4750.    will always be a new version.  It also sets the file protection once it is
  4751.    finished.  The protection that we will use is stored in vms_fab_final_pro,
  4752.    and was set when we did a creat_copy_attrs to create the file that we
  4753.    are renaming.
  4754.  
  4755.    We could use the chmod function, but Eunichs uses 3 bits per user category
  4756.    to describe the protection, and VMS uses 4 (write and delete are separate
  4757.    bits).  To maintain portability, the VMS implementation of `chmod' wires
  4758.    the W and D bits together.  */
  4759.  
  4760.  
  4761. static char vms_file_written[NAM$C_MAXRSS];
  4762.  
  4763. int
  4764. rename_sans_version (char *from, char *to)
  4765. {
  4766.   short int chan;
  4767.   int stat;
  4768.   short int iosb[4];
  4769.   int status;
  4770.   struct fibdef fib;
  4771.   struct FAB to_fab = cc$rms_fab;
  4772.   struct NAM to_nam = cc$rms_nam;
  4773.   struct dsc$descriptor fib_d ={sizeof (fib),0,0,(char*) &fib};
  4774.   struct dsc$descriptor fib_attr[2]
  4775.     = {{sizeof (vms_fab_final_pro),ATR$C_FPRO,0,(char*) &vms_fab_final_pro},{0,0,0,0}};
  4776.   char to_esn[NAM$C_MAXRSS];
  4777.  
  4778.   $DESCRIPTOR (disk,to_esn);
  4779.  
  4780.   memset (&fib, 0, sizeof (fib));
  4781.  
  4782.   to_fab.fab$l_fna = to;
  4783.   to_fab.fab$b_fns = strlen (to);
  4784.   to_fab.fab$l_nam = &to_nam;
  4785.   to_fab.fab$l_fop = FAB$M_NAM;
  4786.  
  4787.   to_nam.nam$l_esa = to_esn;
  4788.   to_nam.nam$b_ess = sizeof to_esn;
  4789.  
  4790.   status = SYS$PARSE (&to_fab, 0, 0); /* figure out the full file name */
  4791.  
  4792.   if (to_nam.nam$l_fnb && NAM$M_EXP_VER)
  4793.     *(to_nam.nam$l_ver) = '\0';
  4794.  
  4795.   stat = rename (from, to_esn);
  4796.   if (stat < 0)
  4797.     return stat;
  4798.  
  4799.   strcpy (vms_file_written, to_esn);
  4800.  
  4801.   to_fab.fab$l_fna = vms_file_written; /* this points to the versionless name */
  4802.   to_fab.fab$b_fns = strlen (vms_file_written);
  4803.  
  4804.   /* Now set the file protection to the correct value */
  4805.   SYS$OPEN (&to_fab, 0, 0);    /* This fills in the nam$w_fid fields */
  4806.  
  4807.   /* Copy these fields into the fib */
  4808.   fib.fib$r_fid_overlay.fib$w_fid[0] = to_nam.nam$w_fid[0];
  4809.   fib.fib$r_fid_overlay.fib$w_fid[1] = to_nam.nam$w_fid[1];
  4810.   fib.fib$r_fid_overlay.fib$w_fid[2] = to_nam.nam$w_fid[2];
  4811.  
  4812.   SYS$CLOSE (&to_fab, 0, 0);
  4813.  
  4814.   stat = SYS$ASSIGN (&disk, &chan, 0, 0); /* open a channel to the disk */
  4815.   if (!stat)
  4816.     LIB$SIGNAL (stat);
  4817.   stat = SYS$QIOW (0, chan, IO$_MODIFY, iosb, 0, 0, &fib_d,
  4818.            0, 0, 0, &fib_attr, 0);
  4819.   if (!stat)
  4820.     LIB$SIGNAL (stat);
  4821.   stat = SYS$DASSGN (chan);
  4822.   if (!stat)
  4823.     LIB$SIGNAL (stat);
  4824.   strcpy (vms_file_written, to_esn); /* We will write this to the terminal*/
  4825.   return 0;
  4826. }
  4827.  
  4828. int
  4829. link (char *file, char *new)
  4830. {
  4831.   status;
  4832.   struct FAB fab;
  4833.   struct NAM nam;
  4834.   unsigned short fid[3];
  4835.   char esa[NAM$C_MAXRSS];
  4836.  
  4837.   fab = cc$rms_fab;
  4838.   fab.fab$l_fop = FAB$M_OFP;
  4839.   fab.fab$l_fna = file;
  4840.   fab.fab$b_fns = strlen (file);
  4841.   fab.fab$l_nam = &nam;
  4842.  
  4843.   nam = cc$rms_nam;
  4844.   nam.nam$l_esa = esa;
  4845.   nam.nam$b_ess = NAM$C_MAXRSS;
  4846.  
  4847.   status = SYS$PARSE (&fab);
  4848.   if ((status & 1) == 0)
  4849.     {
  4850.       errno = EVMSERR;
  4851.       vaxc$errno = status;
  4852.       return -1;
  4853.     }
  4854.   status = SYS$SEARCH (&fab);
  4855.   if ((status & 1) == 0)
  4856.     {
  4857.       errno = EVMSERR;
  4858.       vaxc$errno = status;
  4859.       return -1;
  4860.     }
  4861.  
  4862.   fid[0] = nam.nam$w_fid[0];
  4863.   fid[1] = nam.nam$w_fid[1];
  4864.   fid[2] = nam.nam$w_fid[2];
  4865.  
  4866.   fab.fab$l_fna = new;
  4867.   fab.fab$b_fns = strlen (new);
  4868.  
  4869.   status = SYS$PARSE (&fab);
  4870.   if ((status & 1) == 0)
  4871.     {
  4872.       errno = EVMSERR;
  4873.       vaxc$errno = status;
  4874.       return -1;
  4875.     }
  4876.  
  4877.   nam.nam$w_fid[0] = fid[0];
  4878.   nam.nam$w_fid[1] = fid[1];
  4879.   nam.nam$w_fid[2] = fid[2];
  4880.  
  4881.   nam.nam$l_esa = nam.nam$l_name;
  4882.   nam.nam$b_esl = nam.nam$b_name + nam.nam$b_type + nam.nam$b_ver;
  4883.  
  4884.   status = SYS$ENTER (&fab);
  4885.   if ((status & 1) == 0)
  4886.     {
  4887.       errno = EVMSERR;
  4888.       vaxc$errno = status;
  4889.       return -1;
  4890.     }
  4891.  
  4892.   return 0;
  4893. }
  4894.  
  4895. #ifdef getenv
  4896. /* If any place else asks for the TERM variable,
  4897.    allow it to be overridden with the EMACS_TERM variable
  4898.    before attempting to translate the logical name TERM.  As a last
  4899.    resort, ask for VAX C's special idea of the TERM variable.  */
  4900. #undef getenv
  4901. char *
  4902. sys_getenv (char *name)
  4903. {
  4904.   char *val;
  4905.   static char buf[256];
  4906.   static struct dsc$descriptor_s equiv
  4907.     = {sizeof (buf), DSC$K_DTYPE_T, DSC$K_CLASS_S, buf};
  4908.   static struct dsc$descriptor_s d_name
  4909.     = {0, DSC$K_DTYPE_T, DSC$K_CLASS_S, 0};
  4910.   short eqlen;
  4911.  
  4912.   if (!strcmp (name, "TERM"))
  4913.     {
  4914.       val = (char *) getenv ("EMACS_TERM");
  4915.       if (val)
  4916.     return val;
  4917.     }
  4918.  
  4919.   d_name.dsc$w_length = strlen (name);
  4920.   d_name.dsc$a_pointer = name;
  4921.   if (LIB$SYS_TRNLOG (&d_name, &eqlen, &equiv) == 1)
  4922.     {
  4923.       char *str = (char *) xmalloc (eqlen + 1);
  4924.       memcpy (str, buf, eqlen);
  4925.       str[eqlen] = '\0';
  4926.       /* This is a storage leak, but a pain to fix.  With luck,
  4927.      no one will ever notice.  */
  4928.       return str;
  4929.     }
  4930.   return (char *) getenv (name);
  4931. }
  4932. #endif /* getenv */
  4933.  
  4934. #ifdef abort
  4935. /* Since VMS doesn't believe in core dumps, the only way to debug this beast is
  4936.    to force a call on the debugger from within the image. */
  4937. #undef abort
  4938. sys_abort (void)
  4939. {
  4940.   reset_all_devices ();
  4941.   LIB$SIGNAL (SS$_DEBUG);
  4942. }
  4943. #endif /* abort */
  4944.  
  4945. #if 0 /* Apparently unused */
  4946. /* The standard `sleep' routine works some other way
  4947.    and it stops working if you have ever quit out of it.
  4948.    This one continues to work.  */
  4949.  
  4950. void
  4951. sys_sleep (int timeval)
  4952. {
  4953.   int time [2];
  4954.   static int zero = 0;
  4955.   static int large = -10000000;
  4956.  
  4957.   LIB$EMUL (&timeval, &large, &zero, time);       /* Convert to VMS format */
  4958.  
  4959.   SYS$CANTIM (1, 0);
  4960.   if (SYS$SETIMR (vms_timer_ef, time, 0, 1) & 1) /* Set timer */
  4961.     SYS$WAITFR (vms_timer_ef);      /* Wait for timer expiry only */
  4962. }
  4963. #endif /* 0 */
  4964.  
  4965. #endif /* VMS */
  4966.